/**
 * 甘蔗农机智能管控平台 - 弹窗功能模块
 * 所有按钮的专业弹窗实现
 */

// ========== 页面1: 操作首页按钮 ==========

// 开始作业
function startWork() {
    // 检查是否有待执行的任务
    const taskContainer = document.getElementById('task-list-container');
    const pendingTasks = taskContainer ? Array.from(taskContainer.children).filter(card => {
        const badge = card.querySelector('span');
        return badge && badge.textContent === '待执行';
    }) : [];
    
    if (pendingTasks.length === 0) {
        showToast('请先分配任务再开始作业', 'warning');
        return;
    }
    
    // 获取任务信息
    let taskListHtml = '<div style="margin-bottom: 15px; padding: 12px; background: #e3f2fd; border-radius: 4px; border-left: 3px solid #3498db;">';
    taskListHtml += '<div style="font-weight: 600; color: #2c3e50; margin-bottom: 8px;">待执行任务列表</div>';
    pendingTasks.forEach((task, index) => {
        const robotId = task.querySelector('div').textContent.trim();
        const pathName = task.querySelectorAll('div')[2].textContent;
        
        // 读取作业参数
        let paramsInfo = '';
        try {
            const paramsAttr = task.getAttribute('data-work-params');
            if (paramsAttr) {
                const workParams = JSON.parse(paramsAttr);
                if (workParams.auto_adaptive) {
                    paramsInfo = ' (算法自适应)';
                } else {
                    paramsInfo = ` (电机${workParams.motor_speed}m/min, 刀具${workParams.blade_speed}RPM)`;
                }
            }
        } catch(e) {
            console.error('解析参数失败:', e);
        }
        
        taskListHtml += `<div style="font-size: 12px; color: #7f8c8d; margin-bottom: 3px;">${index + 1}. ${robotId} - ${pathName}${paramsInfo}</div>`;
    });
    taskListHtml += '</div>';
    
    const html = `
        <div style="text-align: center;">
            <div class="spinner"></div>
            <h3 style="color: #3498db; font-size: 16px;">正在启动作业系统</h3>
        </div>
        
        ${taskListHtml}
        
        <div class="modal-progress">
            <div class="modal-progress-label">系统自检</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="p1" style="width:0%;">0%</div>
            </div>
        </div>
        
        <div class="modal-progress">
            <div class="modal-progress-label">GPS定位</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="p2" style="width:0%;">0%</div>
            </div>
        </div>
        
        <div class="modal-progress">
            <div class="modal-progress-label">路径加载</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="p3" style="width:0%;">0%</div>
            </div>
        </div>
        
        <div class="log-panel" id="work-log"></div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="confirmStart()">确认启动</button>
            <button class="modal-btn btn-danger" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('启动作业系统', html);
    
    const logs = [
        '[系统] 自检开始...',
        '[检查] 发电机状态 OK',
        '[检查] PLC通信 OK',
        '[检查] 传感器状态 OK',
        `[任务] 检测到 ${pendingTasks.length} 个待执行任务`,
        '[GPS] 定位中...',
        '[GPS] 锁定8颗卫星',
        '[雷达] 连接LD14P...',
        '[雷达] 点云数>300',
        '[路径] 加载路径数据...',
        '[设备] 所有设备就绪',
        '[系统] 准备完毕'
    ];
    
    animateProgress(logs, ['p1', 'p2', 'p3'], 'work-log');
}

function confirmStart() {
    // 启动所有待执行的任务
    const taskContainer = document.getElementById('task-list-container');
    if (taskContainer) {
        const taskCards = taskContainer.children;
        let startedCount = 0;
        
        Array.from(taskCards).forEach(card => {
            const badge = card.querySelector('span');
            if (badge && badge.textContent === '待执行') {
                // 更新状态为执行中
                badge.textContent = '执行中';
                badge.style.background = '#27ae60';
                
                // 禁用开始按钮
                const buttons = card.querySelectorAll('button');
                if (buttons.length > 1) {
                    buttons[1].disabled = true;
                    buttons[1].style.opacity = '0.5';
                    buttons[1].style.cursor = 'not-allowed';
                }
                
                startedCount++;
            }
        });
        
        console.log(`[作业启动] 已启动 ${startedCount} 个任务`);
    }
    
    socket.emit('work_command', {action: 'start'});
    showToast('作业系统已启动，任务开始执行', 'success');
    closeModal();
}

// 停止作业
function stopWork() {
    // 检查是否有执行中的任务
    const taskContainer = document.getElementById('task-list-container');
    const runningTasks = taskContainer ? Array.from(taskContainer.children).filter(card => {
        const badge = card.querySelector('span');
        return badge && badge.textContent === '执行中';
    }) : [];
    
    if (runningTasks.length === 0) {
        showToast('当前没有正在执行的任务', 'info');
        return;
    }
    
    // 获取执行中的任务信息
    let taskListHtml = '<div style="margin-bottom: 15px; padding: 12px; background: #fff3cd; border-radius: 4px; border-left: 3px solid #f39c12;">';
    taskListHtml += '<div style="font-weight: 600; color: #856404; margin-bottom: 8px;">执行中的任务</div>';
    runningTasks.forEach((task, index) => {
        const robotId = task.querySelector('div').textContent.trim();
        const pathName = task.querySelectorAll('div')[2].textContent;
        taskListHtml += `<div style="font-size: 12px; color: #856404; margin-bottom: 3px;">${index + 1}. ${robotId} - ${pathName}</div>`;
    });
    taskListHtml += '</div>';
    
    const html = `
        <div style="text-align: center; padding: 25px 0;">
            <div style="width: 80px; height: 80px; border-radius: 50%; background: #fadbd8; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; border: 3px solid #e74c3c;">
                <span style="font-size: 40px; color: #e74c3c;">!</span>
            </div>
            <h3 style="color: #e74c3c; font-size: 18px; margin-bottom: 10px;">确认停止作业？</h3>
            <p style="color: #7f8c8d; font-size: 14px;">将停止所有执行中的任务，当前进度将被保存</p>
        </div>
        
        ${taskListHtml}
        
        <div class="modal-grid">
            <div class="modal-card">
                <div class="modal-card-label">执行任务</div>
                <div class="modal-card-value">${runningTasks.length}</div>
                <div class="modal-card-unit">个</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">完成面积</div>
                <div class="modal-card-value">12.3</div>
                <div class="modal-card-unit">亩</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">任务进度</div>
                <div class="modal-card-value">67</div>
                <div class="modal-card-unit">%</div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-danger" onclick="confirmStop()">确认停止</button>
            <button class="modal-btn btn-primary" onclick="closeModal()">继续作业</button>
        </div>
    `;
    
    showModal('停止作业确认', html);
}

function confirmStop() {
    // 停止所有执行中的任务
    const taskContainer = document.getElementById('task-list-container');
    if (taskContainer) {
        const taskCards = taskContainer.children;
        let stoppedCount = 0;
        
        Array.from(taskCards).forEach(card => {
            const badge = card.querySelector('span');
            if (badge && badge.textContent === '执行中') {
                // 更新状态为已停止
                badge.textContent = '已停止';
                badge.style.background = '#95a5a6';
                
                // 启用开始按钮
                const buttons = card.querySelectorAll('button');
                if (buttons.length > 1) {
                    buttons[1].disabled = false;
                    buttons[1].style.opacity = '1';
                    buttons[1].style.cursor = 'pointer';
                    buttons[1].textContent = '恢复';
                }
                
                stoppedCount++;
            }
        });
        
        console.log(`[作业停止] 已停止 ${stoppedCount} 个任务`);
    }
    
    socket.emit('work_command', {action: 'stop'});
    showToast('作业已停止，任务已暂停', 'success');
    closeModal();
}

// 作业管理
function showWorkManage() {
    // 从左下角任务面板读取真实任务状态
    const taskContainer = document.getElementById('task-list-container');
    let runningCount = 0, pendingCount = 0, stoppedCount = 0;
    let taskRows = '';
    
    if (taskContainer && taskContainer.children.length > 0) {
        // 有真实任务
        Array.from(taskContainer.children).forEach((card, index) => {
            const badge = card.querySelector('span');
            const status = badge ? badge.textContent : '未知';
            const robotId = card.querySelector('div').textContent.trim();
            const pathName = card.querySelectorAll('div')[2].textContent;
            const time = new Date().toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit', second: '2-digit'});
            
            let statusBadge = '';
            let actionBtn = '';
            
            if (status === '执行中') {
                runningCount++;
                statusBadge = '<span class="badge badge-success">执行中</span>';
                actionBtn = '<button class="btn btn-primary" style="padding: 5px 12px; font-size: 12px;" onclick="viewTask(' + index + ')">详情</button>';
            } else if (status === '待执行') {
                pendingCount++;
                statusBadge = '<span class="badge badge-warning">待执行</span>';
                actionBtn = '<button class="btn btn-success" style="padding: 5px 12px; font-size: 12px;" onclick="startTask(' + index + ')">启动</button>';
            } else {
                stoppedCount++;
                statusBadge = '<span class="badge badge-default">已停止</span>';
                actionBtn = '<button class="btn btn-default" style="padding: 5px 12px; font-size: 12px;" onclick="viewTask(' + index + ')">查看</button>';
            }
            
            taskRows += `
                <tr>
                    <td>#2024-${String(index + 1).padStart(3, '0')}</td>
                    <td>${robotId}</td>
                    <td>${time}</td>
                    <td>${statusBadge}</td>
                    <td>${actionBtn}</td>
                </tr>
            `;
        });
    } else {
        // 无任务，显示示例数据
        pendingCount = 0;
        runningCount = 0;
        stoppedCount = 0;
        taskRows = `
            <tr>
                <td colspan="5" style="text-align: center; color: #95a5a6; padding: 30px;">
                    暂无作业任务<br><small style="font-size: 12px;">请先在首页进行路径任务分配</small>
                </td>
            </tr>
        `;
    }
    
    const totalCompleted = 128; // 历史已完成任务数
    
    const html = `
        <div style="margin-bottom: 20px;">
            <span class="badge badge-success">执行中: ${runningCount}</span>
            <span class="badge badge-warning">待执行: ${pendingCount}</span>
            <span class="badge badge-default">已停止: ${stoppedCount}</span>
            <span class="badge badge-info">历史完成: ${totalCompleted}</span>
        </div>
        
        <table class="data-table">
            <thead>
                <tr>
                    <th>任务ID</th>
                    <th>机器人</th>
                    <th>时间</th>
                    <th>状态</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                ${taskRows}
            </tbody>
        </table>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="refreshTasks()">刷新列表</button>
            <button class="modal-btn btn-success" onclick="showPathAssignment(); closeModal();">新建任务</button>
        </div>
    `;
    
    showModal('作业管理中心', html);
}

function viewTask(id) { showToast(`查看任务 #${id}`, 'info'); }
function startTask(id) { 
    showToast(`启动任务 #${id}`, 'success'); 
    closeModal();
    // 触发开始作业流程
    setTimeout(() => {
        startWork();
    }, 300);
}
function refreshTasks() { 
    showToast('任务列表已刷新', 'info'); 
    // 重新打开作业管理窗口以刷新数据
    closeModal();
    setTimeout(() => {
        showWorkManage();
    }, 300);
}
function newTask() { showToast('创建新任务', 'success'); }

// 作业评估
function showWorkEval() {
    // 检查是否有任务正在执行
    const taskContainer = document.getElementById('task-list-container');
    let runningCount = 0, totalTasks = 0;
    
    if (taskContainer) {
        totalTasks = taskContainer.children.length;
        Array.from(taskContainer.children).forEach(card => {
            const badge = card.querySelector('span');
            if (badge && badge.textContent === '执行中') {
                runningCount++;
            }
        });
    }
    
    // 根据任务状态生成实时或历史数据
    let statusHtml = '';
    if (runningCount > 0) {
        statusHtml = `
            <div style="background: #d4edda; padding: 12px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #27ae60;">
                <div style="font-weight: 600; color: #155724; margin-bottom: 5px;">实时作业监控</div>
                <div style="font-size: 13px; color: #155724;">当前有 ${runningCount} 个任务正在执行中，以下为实时统计数据</div>
            </div>
        `;
    } else if (totalTasks > 0) {
        statusHtml = `
            <div style="background: #fff3cd; padding: 12px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #f39c12;">
                <div style="font-weight: 600; color: #856404; margin-bottom: 5px;">任务待执行</div>
                <div style="font-size: 13px; color: #856404;">有 ${totalTasks} 个任务等待执行，显示历史数据</div>
            </div>
        `;
    } else {
        statusHtml = `
            <div style="background: #e3f2fd; padding: 12px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #3498db;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 5px;">历史数据统计</div>
                <div style="font-size: 13px; color: #7f8c8d;">暂无进行中的任务，显示历史作业数据</div>
            </div>
        `;
    }
    
    const html = `
        ${statusHtml}
        
        <div class="modal-grid">
            <div class="modal-card">
                <div class="modal-card-label">总作业时长</div>
                <div class="modal-card-value">126.5</div>
                <div class="modal-card-unit">小时</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">完成面积</div>
                <div class="modal-card-value">485</div>
                <div class="modal-card-unit">亩</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">平均效率</div>
                <div class="modal-card-value">3.8</div>
                <div class="modal-card-unit">亩/小时</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">成功率</div>
                <div class="modal-card-value">96.7</div>
                <div class="modal-card-unit">%</div>
            </div>
        </div>
        
        <div style="margin-top: 25px;">
            <h4 style="color: #2c3e50; font-size: 15px; margin-bottom: 12px;">本周作业统计</h4>
            <div style="background: #f8f9fa; padding: 15px; border-radius: 6px;">
                ${generateWeekStats()}
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="exportEval()">导出报告</button>
            <button class="modal-btn btn-success" onclick="showChart()">图表分析</button>
        </div>
    `;
    
    showModal('作业评估报告', html);
}

function generateWeekStats() {
    const days = ['周一', '周二', '周三', '周四', '周五'];
    const values = [18.5, 22.3, 19.8, '维护中', 25.1];
    return days.map((day, i) => `
        <div style="display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px solid #ecf0f1;">
            <span style="color: #7f8c8d;">${day}</span>
            <span style="color: ${typeof values[i] === 'number' ? '#27ae60' : '#f39c12'}; font-weight: 600;">${typeof values[i] === 'number' ? values[i] + ' 亩' : values[i]}</span>
        </div>
    `).join('');
}

function exportEval() { showToast('报告已导出', 'success'); closeModal(); }
function showChart() { showToast('生成图表分析', 'info'); }

// 生成报告
// 路径任务分配
function showPathAssignment() {
    // 获取所有可用的路径
    fetch('/api/gis/map/MAP-001/paths')
        .then(r => r.json())
        .then(data => {
            const paths = data.paths || [];
            const pathOptions = paths.map(p => `
                <option value="${p.id}">${p.name} (${p.point_count}点, ${p.length}m)</option>
            `).join('');
            
            const html = `
                <div style="padding: 20px;">
                    <div style="background: #e3f2fd; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #3498db;">
                        <div style="font-weight: 600; color: #2c3e50; margin-bottom: 8px;">路径任务分配</div>
                        <div style="font-size: 13px; color: #7f8c8d;">为机器人分配作业路径，机器人将按照路径执行自动作业任务</div>
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; color: #7f8c8d; margin-bottom: 10px; font-size: 14px; font-weight: 600;">选择机器人</label>
                        <select id="assign-robot" style="width: 100%; padding: 12px; border: 2px solid #bdc3c7; border-radius: 6px; font-size: 14px; background: white;">
                            <option value="GZJY001">GZJY001 机器人</option>
                            <option value="GZJY002">GZJY002 机器人</option>
                        </select>
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; color: #7f8c8d; margin-bottom: 10px; font-size: 14px; font-weight: 600;">选择作业路径</label>
                        <select id="assign-path" style="width: 100%; padding: 12px; border: 2px solid #bdc3c7; border-radius: 6px; font-size: 14px; background: white;">
                            <option value="">-- 请选择路径 --</option>
                            ${pathOptions}
                        </select>
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <label style="display: block; color: #7f8c8d; margin-bottom: 10px; font-size: 14px; font-weight: 600;">作业模式</label>
                        <select id="assign-mode" style="width: 100%; padding: 12px; border: 2px solid #bdc3c7; border-radius: 6px; font-size: 14px; background: white;">
                            <option value="auto">自动模式</option>
                            <option value="semi">半自动模式</option>
                            <option value="manual">手动模式</option>
                        </select>
                    </div>
                    
                    <div style="background: #e8f5e9; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #27ae60;">
                        <div style="font-weight: 600; color: #27ae60; margin-bottom: 12px;">作业参数设置</div>
                        
                        <div style="margin-bottom: 15px;">
                            <label style="display: flex; align-items: center; margin-bottom: 10px;">
                                <input type="checkbox" id="auto-adaptive" onchange="toggleAutoAdaptive()" style="width: 18px; height: 18px; margin-right: 8px; cursor: pointer;">
                                <span style="color: #2c3e50; font-weight: 600; font-size: 14px;">算法自适应（推荐）</span>
                            </label>
                            <div style="font-size: 12px; color: #7f8c8d; margin-left: 26px;">系统根据地形和作物密度自动调节参数</div>
                        </div>
                        
                        <div id="manual-params" style="display: block;">
                            <div style="margin-bottom: 15px;">
                                <label style="display: block; color: #2c3e50; margin-bottom: 8px; font-size: 13px; font-weight: 600;">电机速度 (m/min)</label>
                                <div style="display: flex; align-items: center; gap: 10px;">
                                    <input type="range" id="motor-speed" min="10" max="80" value="40" oninput="updateMotorSpeed(this.value)" style="flex: 1;">
                                    <span id="motor-speed-value" style="min-width: 80px; padding: 6px 12px; background: white; border-radius: 4px; font-weight: 600; color: #3498db; text-align: center;">40 m/min</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; font-size: 11px; color: #95a5a6; margin-top: 4px;">
                                    <span>慢速 10</span>
                                    <span>中速 40</span>
                                    <span>快速 80</span>
                                </div>
                            </div>
                            
                            <div style="margin-bottom: 0;">
                                <label style="display: block; color: #2c3e50; margin-bottom: 8px; font-size: 13px; font-weight: 600;">刀具转速 (RPM)</label>
                                <div style="display: flex; align-items: center; gap: 10px;">
                                    <input type="range" id="blade-speed" min="500" max="3000" value="1800" step="100" oninput="updateBladeSpeed(this.value)" style="flex: 1;">
                                    <span id="blade-speed-value" style="min-width: 80px; padding: 6px 12px; background: white; border-radius: 4px; font-weight: 600; color: #27ae60; text-align: center;">1800 RPM</span>
                                </div>
                                <div style="display: flex; justify-content: space-between; font-size: 11px; color: #95a5a6; margin-top: 4px;">
                                    <span>低速 500</span>
                                    <span>标准 1800</span>
                                    <span>高速 3000</span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div style="background: #fff3cd; padding: 12px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #f39c12;">
                        <div style="font-size: 13px; color: #856404;">
                            <strong>注意：</strong>分配任务后，机器人将立即接收任务指令，但需要手动启动作业。
                        </div>
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 25px;">
                        <button class="btn btn-success" onclick="confirmPathAssignment()" style="padding: 12px; font-size: 15px; font-weight: 600;">分配任务</button>
                        <button class="btn btn-default" onclick="closeModal()" style="padding: 12px; font-size: 15px;">取消</button>
                    </div>
                </div>
            `;
            
            showModal('路径任务分配', html);
        })
        .catch(e => {
            console.error('[任务分配] 获取路径列表失败:', e);
            showToast('获取路径列表失败', 'danger');
        });
}

// 更新电机速度显示
function updateMotorSpeed(value) {
    document.getElementById('motor-speed-value').textContent = value + ' m/min';
}

// 更新刀具转速显示
function updateBladeSpeed(value) {
    document.getElementById('blade-speed-value').textContent = value + ' RPM';
}

// 切换自适应模式
function toggleAutoAdaptive() {
    const isAdaptive = document.getElementById('auto-adaptive').checked;
    const manualParams = document.getElementById('manual-params');
    
    if (isAdaptive) {
        manualParams.style.display = 'none';
        manualParams.style.opacity = '0.5';
        showToast('已启用算法自适应，系统将自动优化参数', 'info');
    } else {
        manualParams.style.display = 'block';
        manualParams.style.opacity = '1';
        showToast('已切换为手动参数设置', 'info');
    }
}

// 确认分配任务
function confirmPathAssignment() {
    const robotId = document.getElementById('assign-robot').value;
    const pathId = document.getElementById('assign-path').value;
    const mode = document.getElementById('assign-mode').value;
    
    // 获取作业参数
    const isAutoAdaptive = document.getElementById('auto-adaptive').checked;
    const motorSpeed = document.getElementById('motor-speed').value;
    const bladeSpeed = document.getElementById('blade-speed').value;
    
    if (!pathId) {
        showToast('请选择作业路径', 'warning');
        return;
    }
    
    // 获取路径详情
    fetch(`/api/gis/map/MAP-001/paths`)
        .then(r => r.json())
        .then(data => {
            const path = data.paths.find(p => p.id === pathId);
            if (!path) {
                showToast('路径不存在', 'danger');
                return;
            }
            
            // 发送任务给机器人
            const task = {
                type: 'path_task',
                robot_id: robotId,
                path_id: pathId,
                path_name: path.name,
                path_points: path.points,
                mode: mode,
                work_params: {
                    auto_adaptive: isAutoAdaptive,
                    motor_speed: isAutoAdaptive ? 'auto' : parseInt(motorSpeed),
                    blade_speed: isAutoAdaptive ? 'auto' : parseInt(bladeSpeed)
                },
                timestamp: Date.now()
            };
            
            // 通过SocketIO发送任务（如果连接存在）
            if (typeof socket !== 'undefined' && socket.connected) {
                socket.emit('assign_task', task);
                console.log('[任务分配] 发送任务:', task);
            }
            
            // 也保存到本地任务列表
            if (typeof window.assignedTasks === 'undefined') {
                window.assignedTasks = [];
            }
            window.assignedTasks.push({
                ...task,
                status: '已分配',
                assigned_time: new Date().toLocaleString()
            });
            
            closeModal();
            showToast(`任务已分配给 ${robotId}: ${path.name}`, 'success');
            
            // 更新左下角任务栏
            updateTaskStatusPanel(robotId, path, mode, task.work_params);
            
            // 在首页地图显示路径
            if (typeof showTaskPathOnHomeMap === 'function') {
                showTaskPathOnHomeMap(pathId, path.name);
            }
            
            // 显示任务详情
            setTimeout(() => {
                showAssignedTaskDetails(robotId, path, task.work_params);
            }, 500);
        })
        .catch(e => {
            console.error('[任务分配] 分配失败:', e);
            showToast('任务分配失败', 'danger');
        });
}

// 显示已分配任务详情
function showAssignedTaskDetails(robotId, path, workParams) {
    // 构建参数显示HTML
    let paramsHtml = '';
    if (workParams) {
        if (workParams.auto_adaptive) {
            paramsHtml = `
                <div style="background: #e8f5e9; padding: 12px; border-radius: 6px; margin-bottom: 15px; border-left: 4px solid #27ae60;">
                    <div style="font-weight: 600; color: #27ae60; margin-bottom: 5px;">作业参数</div>
                    <div style="font-size: 13px; color: #155724;">
                        <div>算法自适应：已启用</div>
                        <div style="font-size: 11px; opacity: 0.8; margin-top: 3px;">系统将根据地形和作物密度自动调节参数</div>
                    </div>
                </div>
            `;
        } else {
            paramsHtml = `
                <div style="background: #e8f5e9; padding: 12px; border-radius: 6px; margin-bottom: 15px; border-left: 4px solid #27ae60;">
                    <div style="font-weight: 600; color: #27ae60; margin-bottom: 8px;">作业参数</div>
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                        <div>
                            <div style="color: #7f8c8d; font-size: 12px;">电机速度</div>
                            <div style="font-size: 16px; font-weight: 600; color: #3498db;">${workParams.motor_speed} m/min</div>
                        </div>
                        <div>
                            <div style="color: #7f8c8d; font-size: 12px;">刀具转速</div>
                            <div style="font-size: 16px; font-weight: 600; color: #27ae60;">${workParams.blade_speed} RPM</div>
                        </div>
                    </div>
                </div>
            `;
        }
    }
    
    const html = `
        <div style="padding: 20px;">
            <div style="background: #d4edda; padding: 15px; border-radius: 6px; margin-bottom: 20px; border-left: 4px solid #27ae60;">
                <div style="font-weight: 600; color: #155724; margin-bottom: 8px;">任务分配成功</div>
                <div style="font-size: 13px; color: #155724;">机器人已接收任务指令，可以开始作业</div>
            </div>
            
            <div style="margin-bottom: 15px;">
                <div style="color: #7f8c8d; font-size: 13px;">机器人</div>
                <div style="font-size: 16px; font-weight: 600; color: #2c3e50;">${robotId}</div>
            </div>
            
            <div style="margin-bottom: 15px;">
                <div style="color: #7f8c8d; font-size: 13px;">作业路径</div>
                <div style="font-size: 16px; font-weight: 600; color: #2c3e50;">${path.name}</div>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                <div>
                    <div style="color: #7f8c8d; font-size: 13px;">路径点数</div>
                    <div style="font-size: 18px; font-weight: 600; color: #3498db;">${path.point_count} 点</div>
                </div>
                <div>
                    <div style="color: #7f8c8d; font-size: 13px;">路径长度</div>
                    <div style="font-size: 18px; font-weight: 600; color: #3498db;">${path.length} m</div>
                </div>
            </div>
            
            ${paramsHtml}
            
            <div style="background: #e3f2fd; padding: 12px; border-radius: 6px; margin-bottom: 20px;">
                <div style="font-size: 13px; color: #2c3e50;">
                    下一步：切换到"远程控制"页面，点击"开始作业"按钮启动机器人
                </div>
            </div>
            
            <button class="btn btn-primary" onclick="closeModal()" style="width: 100%; padding: 12px; font-size: 15px; font-weight: 600;">确定</button>
        </div>
    `;
    
    showModal('任务分配详情', html);
}

// 更新左下角任务状态面板
function updateTaskStatusPanel(robotId, path, mode, workParams) {
    const panel = document.getElementById('task-status-panel');
    const container = document.getElementById('task-list-container');
    
    if (!panel || !container) {
        console.error('[任务栏] 找不到任务面板元素');
        return;
    }
    
    // 显示任务面板
    panel.style.display = 'block';
    
    // 创建任务卡片
    const taskCard = document.createElement('div');
    taskCard.className = 'task-card';
    taskCard.id = `task-${robotId}-${Date.now()}`;
    taskCard.setAttribute('data-path-id', path.id);
    taskCard.setAttribute('data-path-name', path.name);
    taskCard.setAttribute('data-work-params', JSON.stringify(workParams));
    taskCard.style.cssText = `
        background: #2c3e50;
        padding: 10px;
        border-radius: 4px;
        margin-bottom: 8px;
        border-left: 3px solid #3498db;
        font-size: 11px;
        cursor: pointer;
    `;
    
    const modeText = mode === 'auto' ? '自动' : mode === 'semi' ? '半自动' : '手动';
    const statusColor = '#f39c12';
    
    // 构建参数显示文本
    let paramsText = '';
    if (workParams) {
        if (workParams.auto_adaptive) {
            paramsText = '<div style="color: #27ae60; font-size: 10px; margin-top: 3px;">算法自适应</div>';
        } else {
            paramsText = `<div style="color: #95a5a6; font-size: 9px; margin-top: 3px;">
                电机${workParams.motor_speed}m/min · 刀具${workParams.blade_speed}RPM
            </div>`;
        }
    }
    
    taskCard.innerHTML = `
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 5px;">
            <div style="font-weight: 600; color: #ecf0f1;">${robotId}</div>
            <span style="background: ${statusColor}; color: white; padding: 2px 6px; border-radius: 3px; font-size: 10px;">待执行</span>
        </div>
        <div style="color: #95a5a6; margin-bottom: 3px;">${path.name}</div>
        <div style="color: #7f8c8d; font-size: 10px;">
            ${path.point_count}点 · ${path.length}m · ${modeText}模式
        </div>
        ${paramsText}
        <div style="margin-top: 6px; display: flex; gap: 4px;">
            <button class="task-cancel-btn" style="flex: 1; background: #e74c3c; color: white; border: none; padding: 4px; border-radius: 3px; font-size: 10px; cursor: pointer;">取消</button>
            <button class="task-start-btn" style="flex: 1; background: #27ae60; color: white; border: none; padding: 4px; border-radius: 3px; font-size: 10px; cursor: pointer;">开始</button>
        </div>
    `;
    
    // 点击任务卡片在地图上显示路径
    taskCard.addEventListener('click', function(e) {
        if (e.target.tagName !== 'BUTTON') {
            const pathId = this.getAttribute('data-path-id');
            const pathName = this.getAttribute('data-path-name');
            if (typeof showTaskPathOnHomeMap === 'function') {
                showTaskPathOnHomeMap(pathId, pathName);
                showToast(`地图已定位到: ${pathName}`, 'info');
            }
        }
    });
    
    // 取消按钮事件
    taskCard.querySelector('.task-cancel-btn').addEventListener('click', function(e) {
        e.stopPropagation();
        removeTask(taskCard.id);
    });
    
    // 开始按钮事件
    taskCard.querySelector('.task-start-btn').addEventListener('click', function(e) {
        e.stopPropagation();
        startTaskExecution(robotId, path.id);
    });
    
    container.appendChild(taskCard);
    console.log(`[任务栏] 已添加任务: ${robotId} - ${path.name}`);
}

// 移除任务
function removeTask(taskId) {
    const taskCard = document.getElementById(taskId);
    if (taskCard) {
        taskCard.remove();
        showToast('任务已取消', 'info');
        
        // 如果没有任务了，隐藏面板
        const container = document.getElementById('task-list-container');
        if (container && container.children.length === 0) {
            document.getElementById('task-status-panel').style.display = 'none';
        }
    }
}

// 开始执行任务
function startTaskExecution(robotId, pathId) {
    showToast(`正在启动 ${robotId} 执行任务...`, 'info');
    
    // 更新任务状态为执行中
    const taskCards = document.querySelectorAll('.task-card');
    taskCards.forEach(card => {
        if (card.textContent.includes(robotId)) {
            const statusBadge = card.querySelector('span');
            if (statusBadge) {
                statusBadge.textContent = '执行中';
                statusBadge.style.background = '#27ae60';
            }
            // 禁用开始按钮
            const buttons = card.querySelectorAll('button');
            if (buttons.length > 1) {
                buttons[1].disabled = true;
                buttons[1].style.opacity = '0.5';
                buttons[1].style.cursor = 'not-allowed';
                buttons[1].textContent = '开始';
            }
        }
    });
    
    // 发送启动命令给机器人
    if (typeof socket !== 'undefined' && socket.connected) {
        socket.emit('work_command', {
            action: 'start',
            robot_id: robotId,
            path_id: pathId
        });
    }
    
    console.log(`[任务执行] 机器人: ${robotId}, 路径: ${pathId}`);
}

function generateReport() {
    // 检查任务状态
    const taskContainer = document.getElementById('task-list-container');
    let taskInfo = '';
    let logs = [];
    
    if (taskContainer && taskContainer.children.length > 0) {
        const totalTasks = taskContainer.children.length;
        let runningCount = 0;
        
        Array.from(taskContainer.children).forEach(card => {
            const badge = card.querySelector('span');
            if (badge && badge.textContent === '执行中') {
                runningCount++;
            }
        });
        
        if (runningCount > 0) {
            taskInfo = `<div style="background: #d4edda; padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center; border-left: 3px solid #27ae60;">
                <small style="color: #155724;">检测到 ${runningCount} 个任务执行中，生成实时报告</small>
            </div>`;
            logs = [
                '[检测] 发现执行中任务...',
                '[收集] 实时作业数据...',
                '[处理] GPS轨迹 (1245点)',
                '[分析] 激光雷达扫描数据',
                '[计算] 当前完成面积: 12.5亩',
                '[计算] 已用时长: 2.5小时',
                '[生成] 实时图表统计...',
                '[生成] PDF报告...',
                '[完成] 报告生成成功'
            ];
        } else {
            taskInfo = `<div style="background: #fff3cd; padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center; border-left: 3px solid #f39c12;">
                <small style="color: #856404;">当前有 ${totalTasks} 个任务待执行，生成历史报告</small>
            </div>`;
            logs = [
                '[收集] 历史作业数据...',
                '[处理] GPS轨迹记录',
                '[分析] 作业完成情况',
                '[计算] 总完成面积: 485亩',
                '[计算] 总作业时长: 126.5小时',
                '[生成] 统计图表...',
                '[生成] PDF报告...',
                '[完成] 报告生成成功'
            ];
        }
    } else {
        taskInfo = `<div style="background: #e3f2fd; padding: 10px; border-radius: 4px; margin-bottom: 15px; text-align: center; border-left: 3px solid #3498db;">
            <small style="color: #2c3e50;">暂无任务数据，生成系统总览报告</small>
        </div>`;
        logs = [
            '[收集] 系统历史数据...',
            '[统计] 总作业次数: 128次',
            '[统计] 总完成面积: 485亩',
            '[统计] 总作业时长: 126.5小时',
            '[分析] 设备运行状况',
            '[生成] 系统总览图表...',
            '[生成] PDF报告...',
            '[完成] 报告生成成功'
        ];
    }
    
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #3498db; font-size: 16px;">正在生成作业报告</h3>
        </div>
        
        ${taskInfo}
        
        <div class="log-panel" id="report-log"></div>
        
        <div class="modal-progress">
            <div class="modal-progress-label">生成进度</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="report-p" style="width:0%;">0%</div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="downloadPDF()">下载PDF</button>
            <button class="modal-btn btn-success" onclick="downloadExcel()">下载Excel</button>
        </div>
    `;
    
    showModal('生成作业报告', html);
    
    animateProgress(logs, ['report-p'], 'report-log');
}

function downloadPDF() { showToast('PDF已下载', 'success'); closeModal(); }
function downloadExcel() { showToast('Excel已下载', 'success'); closeModal(); }

// ========== 页面2: 远程控制按钮 ==========

function setMode(mode) {
    const html = `
        <div style="text-align: center; padding: 20px 0;">
            <h3 style="color: #3498db; font-size: 18px; margin-bottom: 15px;">切换控制模式</h3>
            <div style="font-size: 15px; color: #7f8c8d; margin-bottom: 20px;">目标模式: <span style="color: #2c3e50; font-weight: 600;">${mode}</span></div>
        </div>
        
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; margin: 20px 0;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 12px;">模式说明</div>
            <div style="color: #7f8c8d; font-size: 14px; line-height: 1.8;">
                ${getModeDesc(mode)}
            </div>
        </div>
        
        <div class="modal-grid">
            <div class="modal-card">
                <div class="modal-card-label">最大速度</div>
                <div class="modal-card-value">${Math.floor(Math.random()*5)+3}</div>
                <div class="modal-card-unit">km/h</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">响应时间</div>
                <div class="modal-card-value">${Math.floor(Math.random()*50)+50}</div>
                <div class="modal-card-unit">ms</div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="confirmMode('${mode}')">确认切换</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('模式切换', html);
}

function getModeDesc(mode) {
    const descs = {
        '路径分配': '适用于多机器人协同作业的路径分配<br>系统将自动优化路径避免冲突',
        '报警处置': '适用于紧急情况的快速响应处理<br>优先级最高，立即响应操作',
        '手动模式': '适用于完全手动控制机器人运动<br>操作员完全控制，系统不干预',
        '速度1档': '适用于低速精准作业模式<br>降低速度，提高作业精度',
        '单手模式': '适用于单手操作的简化控制<br>减少按键数量，简化操作'
    };
    return descs[mode] || '标准作业模式';
}

function confirmMode(mode) {
    showToast(`已切换到 ${mode}`, 'success');
    closeModal();
}

// 详细操作
function showRemoteDetail() {
    const html = `
        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 20px;">
            <div style="background: #f8f9fa; padding: 20px; border-radius: 6px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">PLC控制指令</div>
                <button class="btn btn-primary" style="width: 100%; margin-bottom: 8px;" onclick="plcCmd('authority')">远程控制权限</button>
                <button class="btn btn-primary" style="width: 100%; margin-bottom: 8px;" onclick="plcCmd('relay')">220V继电器</button>
                <button class="btn btn-primary" style="width: 100%;" onclick="plcCmd('spray')">喷水控制</button>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 6px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">速度调节</div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; color: #7f8c8d; margin-bottom: 5px;">前进速度: <span id="spd-fwd">15</span></label>
                    <input type="range" min="0" max="30" value="15" style="width: 100%;" oninput="updateSpeed('fwd', this.value)">
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="display: block; color: #7f8c8d; margin-bottom: 5px;">转向速度: <span id="spd-turn">8</span></label>
                    <input type="range" min="0" max="15" value="8" style="width: 100%;" oninput="updateSpeed('turn', this.value)">
                </div>
                <button class="btn btn-success" style="width: 100%;" onclick="testForward()">前进测试(5秒)</button>
            </div>
        </div>
        
        <div style="background: #f8f9fa; padding: 15px; border-radius: 6px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 12px;">实时传感器数据</div>
            <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px;">
                <div style="text-align: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0;">
                    <div style="color: #7f8c8d; font-size: 11px;">电压</div>
                    <div style="color: #27ae60; font-size: 18px; font-weight: 700;" id="m-voltage">0V</div>
                </div>
                <div style="text-align: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0;">
                    <div style="color: #7f8c8d; font-size: 11px;">电流</div>
                    <div style="color: #27ae60; font-size: 18px; font-weight: 700;" id="m-current">0A</div>
                </div>
                <div style="text-align: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0;">
                    <div style="color: #7f8c8d; font-size: 11px;">温度</div>
                    <div style="color: #f39c12; font-size: 18px; font-weight: 700;" id="m-temp">0°C</div>
                </div>
                <div style="text-align: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0;">
                    <div style="color: #7f8c8d; font-size: 11px;">油量</div>
                    <div style="color: #3498db; font-size: 18px; font-weight: 700;" id="m-fuel">0%</div>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="refreshSensor()">刷新数据</button>
            <button class="modal-btn btn-danger" onclick="emergencyStop()">紧急停止</button>
        </div>
    `;
    
    showModal('详细操作面板', html);
    startSensorUpdate();
}

function plcCmd(type) {
    const names = {authority: '远程控制权限', relay: '220V继电器', spray: '喷水控制'};
    socket.emit('control_command', {type: type, value: 1});
    showToast(`${names[type]} 已执行`, 'success');
}

function updateSpeed(type, val) {
    document.getElementById('spd-' + type).textContent = val;
}

function testForward() {
    if (confirm('机器将前进5秒，确定执行？')) {
        socket.emit('continuous_forward_test', {duration: 5000});
        showToast('前进测试开始', 'warning');
    }
}

function refreshSensor() { showToast('传感器数据已刷新', 'info'); startSensorUpdate(); }
function emergencyStop() { 
    socket.emit('movement_control', {forward: 0, turn: 0});
    showToast('紧急停止', 'danger'); 
    closeModal(); 
}

let sensorTimer = null;
function startSensorUpdate() {
    if (sensorTimer) clearInterval(sensorTimer);
    sensorTimer = setInterval(() => {
        const voltage = document.getElementById('voltage')?.textContent || '0V';
        const current = document.getElementById('current')?.textContent || '0A';
        const temp = document.getElementById('temp')?.textContent || '0°C';
        const fuel = document.getElementById('fuel')?.textContent || '0%';
        
        if (document.getElementById('m-voltage')) document.getElementById('m-voltage').textContent = voltage;
        if (document.getElementById('m-current')) document.getElementById('m-current').textContent = current;
        if (document.getElementById('m-temp')) document.getElementById('m-temp').textContent = temp;
        if (document.getElementById('m-fuel')) document.getElementById('m-fuel').textContent = fuel;
    }, 1000);
}

// ========== 页面3: 算法模块按钮 ==========

// 甘蔗识别算法
function showSugarcaneDet() {
    const html = `
        <div style="margin-bottom: 20px;">
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                <div style="background: linear-gradient(135deg, #3498db 0%, #2980b9 100%); padding: 25px; border-radius: 8px; color: white;">
                    <div style="font-size: 48px; font-weight: 700; margin-bottom: 10px;">YOLOv8</div>
                    <div style="font-size: 14px; opacity: 0.95;">深度学习目标检测模型</div>
                    <div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid rgba(255,255,255,0.2);">
                        <div style="font-size: 12px; opacity: 0.8;">模型大小: 235MB</div>
                        <div style="font-size: 12px; opacity: 0.8;">训练样本: 15,280张</div>
                    </div>
                </div>
                <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                    <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">实时性能指标</div>
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="color: #7f8c8d; font-size: 13px;">识别准确率</span>
                            <span style="color: #27ae60; font-weight: 600;">98.7%</span>
                        </div>
                        <div style="background: #ecf0f1; height: 8px; border-radius: 4px; overflow: hidden;">
                            <div style="background: #27ae60; height: 100%; width: 98.7%;"></div>
                        </div>
                    </div>
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="color: #7f8c8d; font-size: 13px;">推理速度</span>
                            <span style="color: #3498db; font-weight: 600;">30 FPS</span>
                        </div>
                        <div style="background: #ecf0f1; height: 8px; border-radius: 4px; overflow: hidden;">
                            <div style="background: #3498db; height: 100%; width: 85%;"></div>
                        </div>
                    </div>
                    <div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="color: #7f8c8d; font-size: 13px;">GPU占用</span>
                            <span style="color: #f39c12; font-weight: 600;">68%</span>
                        </div>
                        <div style="background: #ecf0f1; height: 8px; border-radius: 4px; overflow: hidden;">
                            <div style="background: #f39c12; height: 100%; width: 68%;"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div style="background: #e8f5e9; padding: 20px; border-radius: 8px; border-left: 4px solid #27ae60; margin-bottom: 20px;">
                <div style="font-weight: 600; color: #27ae60; margin-bottom: 12px; font-size: 15px;">识别目标分类</div>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
                    <div style="background: white; padding: 15px; border-radius: 6px; text-align: center;">
                        <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">甘蔗茎秆</div>
                        <div style="color: #27ae60; font-size: 24px; font-weight: 700;">99.2%</div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; text-align: center;">
                        <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">甘蔗叶片</div>
                        <div style="color: #27ae60; font-size: 24px; font-weight: 700;">98.5%</div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; text-align: center;">
                        <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">割叶位置</div>
                        <div style="color: #27ae60; font-size: 24px; font-weight: 700;">97.8%</div>
                    </div>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">算法工作流程</div>
                <div style="position: relative;">
                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 15px;">
                        <div style="flex: 1; text-align: center; padding: 12px; background: white; border-radius: 6px; border: 2px solid #3498db;">
                            <div style="font-weight: 600; color: #3498db; margin-bottom: 5px;">1. 图像采集</div>
                            <div style="font-size: 11px; color: #7f8c8d;">1280×720 @ 30fps</div>
                        </div>
                        <div style="width: 30px; text-align: center; color: #3498db;">→</div>
                        <div style="flex: 1; text-align: center; padding: 12px; background: white; border-radius: 6px; border: 2px solid #3498db;">
                            <div style="font-weight: 600; color: #3498db; margin-bottom: 5px;">2. 预处理</div>
                            <div style="font-size: 11px; color: #7f8c8d;">归一化/增强</div>
                        </div>
                        <div style="width: 30px; text-align: center; color: #3498db;">→</div>
                        <div style="flex: 1; text-align: center; padding: 12px; background: white; border-radius: 6px; border: 2px solid #3498db;">
                            <div style="font-weight: 600; color: #3498db; margin-bottom: 5px;">3. 模型推理</div>
                            <div style="font-size: 11px; color: #7f8c8d;">YOLOv8检测</div>
                        </div>
                        <div style="width: 30px; text-align: center; color: #3498db;">→</div>
                        <div style="flex: 1; text-align: center; padding: 12px; background: white; border-radius: 6px; border: 2px solid #27ae60;">
                            <div style="font-weight: 600; color: #27ae60; margin-bottom: 5px;">4. 结果输出</div>
                            <div style="font-size: 11px; color: #7f8c8d;">边界框/置信度</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="startDetection()">启动识别</button>
            <button class="modal-btn btn-primary" onclick="calibrateModel()">模型校准</button>
            <button class="modal-btn btn-warning" onclick="viewTrainData()">查看训练数据</button>
        </div>
    `;
    
    showModal('甘蔗识别算法详情', html);
}

function startDetection() { showToast('甘蔗识别算法已启动', 'success'); closeModal(); }
function calibrateModel() { showToast('开始模型校准', 'info'); }
function viewTrainData() { showToast('训练数据集: 15,280张图片', 'info'); }

// 割叶控制算法
function showLeafCutAlgo() {
    const html = `
        <div style="margin-bottom: 20px;">
            <div style="background: linear-gradient(135deg, #27ae60 0%, #229954 100%); padding: 25px; border-radius: 8px; color: white; margin-bottom: 20px;">
                <h3 style="font-size: 24px; margin-bottom: 15px;">智能割叶控制系统</h3>
                <div style="font-size: 14px; opacity: 0.95; line-height: 1.8;">
                    基于视觉反馈的实时刀具高度与角度自适应控制，确保割叶质量与作业效率
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
                <div style="background: #e8f5e9; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #27ae60;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">割叶高度精度</div>
                    <div style="color: #27ae60; font-size: 36px; font-weight: 700;">±2cm</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">符合农艺标准</div>
                </div>
                <div style="background: #e3f2fd; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #3498db;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">刀具响应时间</div>
                    <div style="color: #3498db; font-size: 36px; font-weight: 700;">30ms</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">PID闭环控制</div>
                </div>
                <div style="background: #fef5e7; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #f39c12;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">刀具角度调节</div>
                    <div style="color: #f39c12; font-size: 36px; font-weight: 700;">0-30°</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">电动伺服驱动</div>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">割叶参数自适应调节</div>
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="background: #ecf0f1;">
                            <th style="padding: 12px; text-align: left; font-size: 13px; color: #2c3e50;">甘蔗类型</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">株高范围</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">割叶高度</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">刀具转速</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr style="border-bottom: 1px solid #ecf0f1;">
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">低矮型</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db; font-weight: 600;">< 1.5m</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #27ae60; font-weight: 600;">40-50cm</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">2200 rpm</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #ecf0f1;">
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">中等型</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db; font-weight: 600;">1.5-2.5m</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #27ae60; font-weight: 600;">60-75cm</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">2600 rpm</td>
                        </tr>
                        <tr>
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">高秆型</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db; font-weight: 600;">> 2.5m</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #27ae60; font-weight: 600;">80-100cm</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">3000 rpm</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #f39c12;">
                <div style="font-weight: 600; color: #856404; margin-bottom: 8px;">控制算法特性</div>
                <div style="color: #856404; font-size: 13px; line-height: 2;">
                    • PID闭环控制，实时修正刀具高度偏差<br>
                    • 视觉伺服系统，跟踪甘蔗顶部特征点<br>
                    • 力反馈传感器，检测刀具负载状态<br>
                    • 地面仿形系统，适应地形起伏变化<br>
                    • 左右独立控制，应对甘蔗高度差异
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="startLeafCut()">启动割叶</button>
            <button class="modal-btn btn-primary" onclick="adjustHeight()">高度调节</button>
            <button class="modal-btn btn-warning" onclick="testBlade()">刀具测试</button>
        </div>
    `;
    
    showModal('割叶控制算法详情', html);
}

function startLeafCut() { showToast('割叶系统已启动', 'success'); closeModal(); }
function adjustHeight() { showToast('进入高度调节模式', 'info'); }
function testBlade() { showToast('刀具测试运行中', 'warning'); }

// 甘蔗行识别
function showRowDetect() {
    const html = `
        <div style="margin-bottom: 20px;">
            <div style="background: linear-gradient(135deg, #9b59b6 0%, #8e44ad 100%); padding: 25px; border-radius: 8px; color: white; margin-bottom: 20px;">
                <h3 style="font-size: 24px; margin-bottom: 15px;">甘蔗行识别与跟踪</h3>
                <div style="font-size: 14px; opacity: 0.95; line-height: 1.8;">
                    融合激光雷达点云与视觉图像的多传感器甘蔗行识别算法，实现高精度行跟踪
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                    <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">传感器融合策略</div>
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; background: white; border-radius: 6px; border-left: 3px solid #9b59b6;">
                            <span style="color: #7f8c8d; font-size: 13px;">激光雷达 (360°)</span>
                            <span style="color: #9b59b6; font-weight: 600; font-size: 13px;">权重 60%</span>
                        </div>
                    </div>
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; padding: 10px; background: white; border-radius: 6px; border-left: 3px solid #3498db;">
                            <span style="color: #7f8c8d; font-size: 13px;">视觉相机 (前向)</span>
                            <span style="color: #3498db; font-weight: 600; font-size: 13px;">权重 40%</span>
                        </div>
                    </div>
                    <div style="background: #e8f5e9; padding: 12px; border-radius: 6px; margin-top: 15px;">
                        <div style="color: #27ae60; font-size: 12px; font-weight: 600;">卡尔曼滤波融合</div>
                        <div style="color: #7f8c8d; font-size: 11px; margin-top: 5px;">实时状态估计与预测</div>
                    </div>
                </div>
                
                <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                    <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">识别性能指标</div>
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="color: #7f8c8d; font-size: 13px;">横向偏差</span>
                            <span style="color: #27ae60; font-weight: 600;">< 3cm</span>
                        </div>
                        <div style="background: #ecf0f1; height: 6px; border-radius: 3px; overflow: hidden;">
                            <div style="background: #27ae60; height: 100%; width: 95%;"></div>
                        </div>
                    </div>
                    <div style="margin-bottom: 12px;">
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="color: #7f8c8d; font-size: 13px;">跟踪可靠性</span>
                            <span style="color: #3498db; font-weight: 600;">99.2%</span>
                        </div>
                        <div style="background: #ecf0f1; height: 6px; border-radius: 3px; overflow: hidden;">
                            <div style="background: #3498db; height: 100%; width: 99.2%;"></div>
                        </div>
                    </div>
                    <div>
                        <div style="display: flex; justify-content: space-between; margin-bottom: 5px;">
                            <span style="color: #7f8c8d; font-size: 13px;">更新频率</span>
                            <span style="color: #f39c12; font-weight: 600;">20 Hz</span>
                        </div>
                        <div style="background: #ecf0f1; height: 6px; border-radius: 3px; overflow: hidden;">
                            <div style="background: #f39c12; height: 100%; width: 80%;"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">算法处理流程</div>
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px;">
                    <div style="background: white; padding: 15px; border-radius: 6px; text-align: center; border-top: 3px solid #9b59b6;">
                        <div style="color: #9b59b6; font-weight: 600; margin-bottom: 8px;">1</div>
                        <div style="font-size: 12px; color: #7f8c8d; line-height: 1.6;">点云聚类<br>提取甘蔗行</div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; text-align: center; border-top: 3px solid #3498db;">
                        <div style="color: #3498db; font-weight: 600; margin-bottom: 8px;">2</div>
                        <div style="font-size: 12px; color: #7f8c8d; line-height: 1.6;">图像分割<br>识别甘蔗区域</div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; text-align: center; border-top: 3px solid #f39c12;">
                        <div style="color: #f39c12; font-weight: 600; margin-bottom: 8px;">3</div>
                        <div style="font-size: 12px; color: #7f8c8d; line-height: 1.6;">数据融合<br>卡尔曼滤波</div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; text-align: center; border-top: 3px solid #27ae60;">
                        <div style="color: #27ae60; font-weight: 600; margin-bottom: 8px;">4</div>
                        <div style="font-size: 12px; color: #7f8c8d; line-height: 1.6;">中线计算<br>输出控制量</div>
                    </div>
                </div>
            </div>
            
            <div style="background: #e3f2fd; padding: 15px; border-radius: 8px; border-left: 4px solid #3498db;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 10px;">适应场景</div>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                    <div style="background: white; padding: 12px; border-radius: 4px; border: 1px solid #27ae60;">
                        <div style="color: #27ae60; font-size: 13px; font-weight: 600; margin-bottom: 3px;">规整蔗田</div>
                        <div style="font-size: 11px; color: #7f8c8d;">标准种植场景</div>
                    </div>
                    <div style="background: white; padding: 12px; border-radius: 4px; border: 1px solid #27ae60;">
                        <div style="color: #27ae60; font-size: 13px; font-weight: 600; margin-bottom: 3px;">杂草环境</div>
                        <div style="font-size: 11px; color: #7f8c8d;">复杂干扰场景</div>
                    </div>
                    <div style="background: white; padding: 12px; border-radius: 4px; border: 1px solid #27ae60;">
                        <div style="color: #27ae60; font-size: 13px; font-weight: 600; margin-bottom: 3px;">不同光照</div>
                        <div style="font-size: 11px; color: #7f8c8d;">全天候作业</div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="startRowTracking()">启动行跟踪</button>
            <button class="modal-btn btn-primary" onclick="calibrateSensors()">传感器标定</button>
            <button class="modal-btn btn-default" onclick="viewFusion()">查看融合结果</button>
        </div>
    `;
    
    showModal('甘蔗行识别算法详情', html);
}

function startRowTracking() { showToast('甘蔗行跟踪已启动', 'success'); closeModal(); }
function calibrateSensors() { showToast('传感器标定中', 'info'); }
function viewFusion() { showToast('传感器融合可视化', 'info'); }

// 障碍物检测
function showObstacleAvoid() {
    const html = `
        <div style="margin-bottom: 20px;">
            <div style="background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%); padding: 25px; border-radius: 8px; color: white; margin-bottom: 20px;">
                <h3 style="font-size: 24px; margin-bottom: 15px;">360°障碍物检测系统</h3>
                <div style="font-size: 14px; opacity: 0.95; line-height: 1.8;">
                    基于LD14P激光雷达的实时障碍物检测与预警系统，保障作业安全
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
                <div style="background: #fadbd8; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #e74c3c;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">扫描范围</div>
                    <div style="color: #e74c3c; font-size: 36px; font-weight: 700;">360°</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">全方位覆盖</div>
                </div>
                <div style="background: #fef5e7; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #f39c12;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">检测距离</div>
                    <div style="color: #f39c12; font-size: 36px; font-weight: 700;">0.2-12m</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">远近兼顾</div>
                </div>
                <div style="background: #e3f2fd; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #3498db;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">刷新频率</div>
                    <div style="color: #3498db; font-size: 36px; font-weight: 700;">8 Hz</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">实时响应</div>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">障碍物分类识别</div>
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="background: #ecf0f1;">
                            <th style="padding: 12px; text-align: left; font-size: 13px; color: #2c3e50;">障碍类型</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">检测方法</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">响应策略</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">安全距离</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr style="border-bottom: 1px solid #ecf0f1;">
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">人员</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db;">雷达+视觉</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #e74c3c; font-weight: 600;">立即停车</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">5.0m</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #ecf0f1;">
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">大型障碍</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db;">雷达点云</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #e74c3c; font-weight: 600;">停车+避让</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">3.0m</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #ecf0f1;">
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">小型石块</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db;">雷达密集点</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">减速绕行</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">1.5m</td>
                        </tr>
                        <tr>
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">田埂沟渠</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db;">高度突变</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">停止作业</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">2.0m</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 20px;">
                <div style="background: #fff3cd; padding: 15px; border-radius: 8px; border-left: 4px solid #f39c12;">
                    <div style="font-weight: 600; color: #856404; margin-bottom: 10px;">安全分区策略</div>
                    <div style="color: #856404; font-size: 12px; line-height: 1.8;">
                        <strong>紧急停车区 (0-1.5m):</strong><br>
                        检测到任何障碍物立即停车<br><br>
                        <strong>预警减速区 (1.5-3.0m):</strong><br>
                        降低速度，准备避障动作<br><br>
                        <strong>监控观察区 (3.0-12m):</strong><br>
                        持续跟踪，评估潜在风险
                    </div>
                </div>
                <div style="background: #fadbd8; padding: 15px; border-radius: 8px; border-left: 4px solid #e74c3c;">
                    <div style="font-weight: 600; color: #c0392b; margin-bottom: 10px;">紧急制动系统</div>
                    <div style="color: #7f8c8d; font-size: 12px; line-height: 1.8;">
                        <strong>制动时间:</strong> <span style="color: #e74c3c; font-weight: 600;">< 0.5秒</span><br>
                        <strong>制动距离:</strong> <span style="color: #e74c3c; font-weight: 600;">< 0.8m</span><br>
                        <strong>触发方式:</strong><br>
                        • 雷达检测到紧急区障碍<br>
                        • 视觉识别到人员<br>
                        • 倾角传感器异常<br>
                        • 手动紧急停止按钮
                    </div>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="startObstacleDetect()">启动检测</button>
            <button class="modal-btn btn-primary" onclick="testEmergencyStop()">测试紧急停车</button>
            <button class="modal-btn btn-warning" onclick="viewLidarData()">查看雷达数据</button>
        </div>
    `;
    
    showModal('障碍物检测系统详情', html);
}

function startObstacleDetect() { showToast('障碍物检测系统已启动', 'success'); closeModal(); }
function testEmergencyStop() { 
    if (confirm('将测试紧急制动系统，机器人会立即停止。确认继续？')) {
        showToast('紧急制动测试：停车距离 0.65m', 'warning'); 
    }
}
function viewLidarData() { showToast('查看激光雷达实时点云', 'info'); }

// 路径规划算法
function showPathPlan() {
    const html = `
        <div style="margin-bottom: 20px;">
            <div style="background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%); padding: 25px; border-radius: 8px; color: white; margin-bottom: 20px;">
                <h3 style="font-size: 24px; margin-bottom: 15px;">智能路径规划系统</h3>
                <div style="font-size: 14px; opacity: 0.95; line-height: 1.8;">
                    基于A*算法与动态窗口法的混合路径规划，实现高效避障与平滑轨迹
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
                <div style="background: #fef5e7; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #f39c12;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">规划时间</div>
                    <div style="color: #f39c12; font-size: 36px; font-weight: 700;">60ms</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">实时重规划</div>
                </div>
                <div style="background: #e8f5e9; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #27ae60;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">路径平滑度</div>
                    <div style="color: #27ae60; font-size: 36px; font-weight: 700;">95%</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">B样条优化</div>
                </div>
                <div style="background: #e3f2fd; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #3498db;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">成功率</div>
                    <div style="color: #3498db; font-size: 36px; font-weight: 700;">99.5%</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">规划成功</div>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">混合规划算法架构</div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                    <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #3498db;">
                        <div style="color: #3498db; font-weight: 600; margin-bottom: 10px;">全局规划 (A*)</div>
                        <div style="color: #7f8c8d; font-size: 12px; line-height: 1.8;">
                            • 栅格地图构建 (50cm×50cm)<br>
                            • 启发式搜索最优路径<br>
                            • 考虑转弯代价与路径长度<br>
                            • 更新周期: 5秒
                        </div>
                        <div style="margin-top: 10px; padding: 8px; background: #e3f2fd; border-radius: 4px; text-align: center;">
                            <span style="color: #3498db; font-size: 11px; font-weight: 600;">适用于: 初始路径 / 大范围重规划</span>
                        </div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #f39c12;">
                        <div style="color: #f39c12; font-weight: 600; margin-bottom: 10px;">局部规划 (DWA)</div>
                        <div style="color: #7f8c8d; font-size: 12px; line-height: 1.8;">
                            • 动态窗口速度采样<br>
                            • 实时障碍物避让<br>
                            • 多目标优化评分函数<br>
                            • 更新周期: 100ms
                        </div>
                        <div style="margin-top: 10px; padding: 8px; background: #fef5e7; border-radius: 4px; text-align: center;">
                            <span style="color: #f39c12; font-size: 11px; font-weight: 600;">适用于: 动态避障 / 精细控制</span>
                        </div>
                    </div>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">路径优化目标</div>
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px;">
                    <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #27ae60;">
                        <div style="font-weight: 600; color: #27ae60; font-size: 13px; margin-bottom: 5px;">最短路径</div>
                        <div style="font-size: 11px; color: #7f8c8d;">最小化行驶距离</div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #3498db;">
                        <div style="font-weight: 600; color: #3498db; font-size: 13px; margin-bottom: 5px;">平滑曲线</div>
                        <div style="font-size: 11px; color: #7f8c8d;">减少转向次数</div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #f39c12;">
                        <div style="font-weight: 600; color: #f39c12; font-size: 13px; margin-bottom: 5px;">能耗最优</div>
                        <div style="font-size: 11px; color: #7f8c8d;">降低油耗成本</div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #e74c3c;">
                        <div style="font-weight: 600; color: #e74c3c; font-size: 13px; margin-bottom: 5px;">安全距离</div>
                        <div style="font-size: 11px; color: #7f8c8d;">保持安全间距</div>
                    </div>
                </div>
            </div>
            
            <div style="background: #e8f5e9; padding: 15px; border-radius: 8px; border-left: 4px solid #27ae60;">
                <div style="font-weight: 600; color: #27ae60; margin-bottom: 10px;">适应场景示例</div>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                    <div style="background: white; padding: 12px; border-radius: 4px; border: 1px solid #27ae60;">
                        <div style="color: #27ae60; font-weight: 600; font-size: 13px; margin-bottom: 5px;">复杂地形</div>
                        <div style="color: #7f8c8d; font-size: 11px;">自动绕行石块、田埂等障碍</div>
                    </div>
                    <div style="background: white; padding: 12px; border-radius: 4px; border: 1px solid #27ae60;">
                        <div style="color: #27ae60; font-weight: 600; font-size: 13px; margin-bottom: 5px;">狭窄空间</div>
                        <div style="color: #7f8c8d; font-size: 11px;">最小转弯半径2.5m精准通过</div>
                    </div>
                    <div style="background: white; padding: 12px; border-radius: 4px; border: 1px solid #27ae60;">
                        <div style="color: #27ae60; font-weight: 600; font-size: 13px; margin-bottom: 5px;">动态避障</div>
                        <div style="color: #7f8c8d; font-size: 11px;">实时检测并避让突发障碍物</div>
                    </div>
                    <div style="background: white; padding: 12px; border-radius: 4px; border: 1px solid #27ae60;">
                        <div style="color: #27ae60; font-weight: 600; font-size: 13px; margin-bottom: 5px;">掉头规划</div>
                        <div style="color: #7f8c8d; font-size: 11px;">田头自动规划最优掉头路径</div>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="runPathPlan()">启动规划</button>
            <button class="modal-btn btn-primary" onclick="adjustParams()">参数调节</button>
            <button class="modal-btn btn-warning" onclick="simulatePath()">路径仿真</button>
        </div>
    `;
    
    showModal('路径规划算法详情', html);
}

function runPathPlan() { showToast('路径规划算法已启动', 'success'); closeModal(); }
function adjustParams() { showToast('进入参数调节模式', 'info'); }
function simulatePath() { showToast('启动路径仿真', 'info'); }

// 地形自适应
function showTerrainAdapt() {
    const html = `
        <div style="margin-bottom: 20px;">
            <div style="background: linear-gradient(135deg, #1abc9c 0%, #16a085 100%); padding: 25px; border-radius: 8px; color: white; margin-bottom: 20px;">
                <h3 style="font-size: 24px; margin-bottom: 15px;">地形自适应控制系统</h3>
                <div style="font-size: 14px; opacity: 0.95; line-height: 1.8;">
                    基于IMU姿态传感器与机械液压系统的智能地形适应，确保在复杂地形稳定作业
                </div>
            </div>
            
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
                <div style="background: #d5f4e6; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #1abc9c;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">最大坡度</div>
                    <div style="color: #1abc9c; font-size: 36px; font-weight: 700;">15°</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">横坡/纵坡</div>
                </div>
                <div style="background: #fff3cd; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #f39c12;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">调平时间</div>
                    <div style="color: #f39c12; font-size: 36px; font-weight: 700;">< 2s</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">液压响应</div>
                </div>
                <div style="background: #e3f2fd; padding: 20px; border-radius: 8px; text-align: center; border: 2px solid #3498db;">
                    <div style="color: #7f8c8d; font-size: 13px; margin-bottom: 8px;">姿态精度</div>
                    <div style="color: #3498db; font-size: 36px; font-weight: 700;">±0.5°</div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-top: 5px;">IMU测量</div>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">姿态控制系统组成</div>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
                    <div style="background: white; padding: 15px; border-radius: 6px; border-left: 3px solid #3498db;">
                        <div style="color: #3498db; font-weight: 600; margin-bottom: 8px;">传感器系统</div>
                        <div style="color: #7f8c8d; font-size: 12px; line-height: 1.8;">
                            • 9轴IMU惯性测量单元<br>
                            • 倾角传感器（前后/左右）<br>
                            • 液压位置传感器<br>
                            • 轮速传感器（防滑检测）
                        </div>
                    </div>
                    <div style="background: white; padding: 15px; border-radius: 6px; border-left: 3px solid #1abc9c;">
                        <div style="color: #1abc9c; font-weight: 600; margin-bottom: 8px;">执行机构</div>
                        <div style="color: #7f8c8d; font-size: 12px; line-height: 1.8;">
                            • 前轴液压调平系统<br>
                            • 后轴独立悬挂调节<br>
                            • 底盘高度自适应<br>
                            • 防侧翻主动稳定杆
                        </div>
                    </div>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">地形适应策略</div>
                <table style="width: 100%; border-collapse: collapse;">
                    <thead>
                        <tr style="background: #ecf0f1;">
                            <th style="padding: 12px; text-align: left; font-size: 13px; color: #2c3e50;">地形类型</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">倾角范围</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">调节策略</th>
                            <th style="padding: 12px; text-align: center; font-size: 13px; color: #2c3e50;">速度限制</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr style="border-bottom: 1px solid #ecf0f1;">
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">平坦地形</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #27ae60; font-weight: 600;">< 5°</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db;">常规模式</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #27ae60; font-weight: 600;">100%</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #ecf0f1;">
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">缓坡地形</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">5-10°</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #3498db;">液压调平</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #f39c12; font-weight: 600;">75%</td>
                        </tr>
                        <tr style="border-bottom: 1px solid #ecf0f1;">
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">陡坡地形</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #e74c3c; font-weight: 600;">10-15°</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #e74c3c;">强制调平+防滑</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #e74c3c; font-weight: 600;">50%</td>
                        </tr>
                        <tr>
                            <td style="padding: 12px; font-size: 13px; color: #7f8c8d;">危险坡度</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #e74c3c; font-weight: 600;">> 15°</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #e74c3c; font-weight: 700;">停止作业</td>
                            <td style="padding: 12px; text-align: center; font-size: 13px; color: #e74c3c; font-weight: 700;">报警</td>
                        </tr>
                    </tbody>
                </table>
            </div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                <div style="background: #fadbd8; padding: 15px; border-radius: 8px; border-left: 4px solid #e74c3c;">
                    <div style="font-weight: 600; color: #c0392b; margin-bottom: 10px;">防侧翻保护</div>
                    <div style="color: #7f8c8d; font-size: 12px; line-height: 1.8;">
                        <strong>侧翻预警阈值:</strong> 横坡 > 12°<br>
                        <strong>触发条件:</strong><br>
                        • 横向倾角持续超过阈值<br>
                        • 检测到单侧轮速异常<br>
                        • 液压调平达到极限位置<br>
                        <strong>应急措施:</strong><br>
                        立即停车 → 报警 → 记录位置
                    </div>
                </div>
                <div style="background: #d5f4e6; padding: 15px; border-radius: 8px; border-left: 4px solid #27ae60;">
                    <div style="font-weight: 600; color: #27ae60; margin-bottom: 10px;">防滑控制</div>
                    <div style="color: #7f8c8d; font-size: 12px; line-height: 1.8;">
                        <strong>检测方式:</strong><br>
                        • 轮速差异对比<br>
                        • GPS速度与轮速差值<br>
                        • IMU加速度异常<br>
                        <strong>控制策略:</strong><br>
                        • 降低动力输出<br>
                        • 差速控制防打滑<br>
                        • 必要时切换低速档
                    </div>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="startTerrainAdapt()">启动地形适应</button>
            <button class="modal-btn btn-primary" onclick="calibrateIMU()">IMU校准</button>
            <button class="modal-btn btn-warning" onclick="testHydraulic()">液压测试</button>
        </div>
    `;
    
    showModal('地形自适应系统详情', html);
}

function startTerrainAdapt() { showToast('地形自适应系统已启动', 'success'); closeModal(); }
function calibrateIMU() { showToast('IMU传感器校准中', 'info'); }
function testHydraulic() { showToast('液压系统自检中', 'warning'); }

function startVisionAlgo() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #3498db; font-size: 16px;">启动视觉识别算法</h3>
        </div>
        
        <div class="log-panel" id="vision-log"></div>
        
        <div class="modal-progress">
            <div class="modal-progress-label">加载进度</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="vision-p" style="width:0%;">0%</div>
            </div>
        </div>
        
        <div class="modal-grid">
            <div class="modal-card">
                <div class="modal-card-label">识别精度</div>
                <div class="modal-card-value" style="font-size: 28px;">98.7</div>
                <div class="modal-card-unit">%</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">处理速度</div>
                <div class="modal-card-value" style="font-size: 28px;">60</div>
                <div class="modal-card-unit">fps</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">GPU使用</div>
                <div class="modal-card-value" style="font-size: 28px;" id="gpu-usage">0</div>
                <div class="modal-card-unit">%</div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="confirmVision()">确认启动</button>
            <button class="modal-btn btn-danger" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('视觉识别算法', html);
    
    const logs = [
        '[初始化] 加载神经网络模型',
        '[加载] YOLOv8模型 (235MB)',
        '[GPU] 检测Mali-G610',
        '[GPU] 分配显存 4096MB',
        '[编译] JIT优化',
        '[测试] 推理测试',
        '[测试] 速度 58.3FPS',
        '[连接] 摄像头数据流',
        '[完成] 算法就绪'
    ];
    
    let idx = 0;
    const logEl = document.getElementById('vision-log');
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            
            const pct = Math.round((idx/logs.length)*100);
            document.getElementById('vision-p').style.width = pct + '%';
            document.getElementById('vision-p').textContent = pct + '%';
            
            if (idx > 5) document.getElementById('gpu-usage').textContent = Math.floor(Math.random()*30+60);
            
            idx++;
        } else {
            clearInterval(timer);
        }
    }, 400);
}

function confirmVision() {
    socket.emit('algorithm_command', {type: 'vision', action: 'start'});
    showToast('视觉识别算法已启动', 'success');
    closeModal();
}

function startPathAlgo() {
    const html = `
        <div style="margin-bottom: 20px;">
            <h4 style="color: #27ae60; font-size: 16px; margin-bottom: 15px;">路径规划算法</h4>
            <div style="background: #f8f9fa; padding: 20px; border-radius: 6px;">
                <div style="margin-bottom: 15px;">
                    <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">规划模式</label>
                    <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                        <option>A* 最短路径</option>
                        <option>RRT 快速扩展树</option>
                        <option>DWA 动态窗口法</option>
                        <option>混合算法 (推荐)</option>
                    </select>
                </div>
                <div style="margin-bottom: 15px;">
                    <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">避障距离: <span id="obs-dist">1.5m</span></label>
                    <input type="range" min="0.5" max="3" step="0.1" value="1.5" style="width: 100%;" oninput="document.getElementById('obs-dist').textContent=this.value+'m'">
                </div>
                <div>
                    <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">路径平滑度</label>
                    <input type="range" min="0" max="10" value="7" style="width: 100%;">
                </div>
            </div>
        </div>
        
        <div class="log-panel" id="path-log"></div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="runPathAlgo()">开始规划</button>
            <button class="modal-btn btn-primary" onclick="testAlgo()">算法测试</button>
        </div>
    `;
    
    showModal('路径规划算法', html);
}

function runPathAlgo() {
    const logs = [
        '[初始化] A*算法',
        '[地图] 构建栅格(50x50)',
        '[扫描] 检测障碍物: 12个',
        '[计算] 搜索路径...',
        '[优化] 平滑处理',
        '[验证] 碰撞检测通过',
        '[完成] 生成最优路径'
    ];
    
    const logEl = document.getElementById('path-log');
    let idx = 0;
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            idx++;
        } else {
            clearInterval(timer);
            showToast('路径规划完成', 'success');
        }
    }, 400);
}

function testAlgo() { showToast('算法测试中', 'info'); }

function startAutoWork() {
    const html = `
        <div style="text-align: center; padding: 20px 0;">
            <h3 style="color: #f39c12; font-size: 18px; margin-bottom: 15px;">全自动作业模式</h3>
            <div style="color: #7f8c8d; font-size: 14px; line-height: 2; text-align: left; max-width: 500px; margin: 0 auto;">
                系统将自动完成以下流程:<br>
                • 自动识别作业区域<br>
                • 自动规划最优路径<br>
                • 自动避障和转弯<br>
                • 自动返回充电/加油
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 15px; border-radius: 6px; margin: 20px 0; border-left: 4px solid #f39c12;">
            <div style="font-weight: 600; color: #856404; margin-bottom: 8px;">重要提示</div>
            <div style="color: #856404; font-size: 13px; line-height: 1.8;">
                • 启动前请确保作业区域无人员<br>
                • 系统会自动检测并避开障碍物<br>
                • 遇到紧急情况按空格键停止
            </div>
        </div>
        
        <div class="modal-grid">
            <div class="modal-card">
                <div class="modal-card-label">预计面积</div>
                <div class="modal-card-value" style="font-size: 28px;">35.8</div>
                <div class="modal-card-unit">亩</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">预计时长</div>
                <div class="modal-card-value" style="font-size: 28px;">4.2</div>
                <div class="modal-card-unit">小时</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">燃料消耗</div>
                <div class="modal-card-value" style="font-size: 28px;">12</div>
                <div class="modal-card-unit">升</div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="confirmAutoWork()">确认启动</button>
            <button class="modal-btn btn-danger" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('全自动作业模式', html);
}

function confirmAutoWork() {
    socket.emit('algorithm_command', {type: 'auto', action: 'start'});
    showToast('全自动作业已启动', 'success');
    closeModal();
}

// ========== 页面4: GIS模块按钮 ==========

// 新建路径 - 直接跳转到绘制路径
function createNewPath() {
    drawPath();
}

// 编辑路径
function editPath(id) {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">路径信息编辑</div>
            
            <table style="width: 100%; border-collapse: collapse; margin-bottom: 20px;">
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 10px; color: #7f8c8d; width: 120px;">路径编号</td>
                    <td style="padding: 10px; font-weight: 600; color: #3498db;">PATH-00${id}</td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 10px; color: #7f8c8d;">点位数量</td>
                    <td style="padding: 10px; color: #2c3e50;">${24 + id * 6} 个</td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 10px; color: #7f8c8d;">路径长度</td>
                    <td style="padding: 10px; color: #27ae60; font-weight: 600;">${(385 + id * 50).toFixed(1)} m</td>
                </tr>
            </table>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">路径名称</label>
                <input type="text" value="东区${id}号作业线" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
            </div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">路径优化</label>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                    <button class="btn btn-primary" onclick="smoothPath()">平滑处理</button>
                    <button class="btn btn-warning" onclick="simplifyPath()">简化路径</button>
                </div>
            </div>
            
            <div>
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">路径调整</label>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                    <button class="btn btn-default" onclick="reversePathDir()">反向</button>
                    <button class="btn btn-default" onclick="offsetPath()">偏移</button>
                    <button class="btn btn-default" onclick="extendPath()">延伸</button>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="savePathEdit()">保存修改</button>
            <button class="modal-btn btn-primary" onclick="previewPath()">预览路径</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('编辑路径 PATH-00' + id, html);
}

function smoothPath() { showToast('路径平滑处理完成', 'success'); }
function simplifyPath() { showToast('路径简化完成，减少15个点位', 'success'); }
function reversePathDir() { showToast('路径方向已反向', 'info'); }
function offsetPath() { showToast('设置偏移距离', 'info'); }
function extendPath() { showToast('路径延伸设置', 'info'); }
function savePathEdit() { showToast('路径修改已保存', 'success'); closeModal(); }
function previewPath() { showToast('在地图上预览路径', 'info'); }

// 加载路径
function loadPath(id) {
    const pathId = `PATH-00${id}`;
    
    // 从gisData中查找路径
    fetch('/api/gis/paths')
        .then(r => r.json())
        .then(data => {
            const path = data.paths.find(p => p.id === pathId);
            if (path && gisMap) {
                // 定位到路径中心
                const bounds = L.latLngBounds(path.points);
                gisMap.fitBounds(bounds, { padding: [50, 50] });
                
                // 高亮显示路径
                const layer = pathLayers[pathId];
                if (layer) {
                    layer.setStyle({ weight: 5, opacity: 1 });
                    layer.openPopup();
                    
                    // 3秒后恢复
                    setTimeout(() => {
                        layer.setStyle({ weight: 3, opacity: 0.8 });
                    }, 3000);
                }
                
                showToast(`路径 ${path.name} 已定位，${path.points.length}个点位`, 'success');
            } else {
                showToast(`路径 ${pathId} 未找到`, 'warning');
            }
        });
}

// 删除路径（已废弃，使用 index.html 中的新版本）
function deletePath(pathId) {
    console.warn('[modals.js] deletePath 已废弃，调用新版本');
    const mapId = (typeof currentMapId !== 'undefined' ? currentMapId : null) || 'MAP-001';
    
    fetch(`/api/gis/map/${mapId}/delete_path/${pathId}`, { method: 'DELETE' })
        .then(r => r.json())
        .then(result => {
            if (result.success) {
                const layer = typeof pathLayers !== 'undefined' && pathLayers[pathId];
                if (layer && typeof gisMap !== 'undefined' && gisMap) {
                    gisMap.removeLayer(layer);
                    delete pathLayers[pathId];
                }
                if (typeof visiblePaths !== 'undefined') {
                    visiblePaths.delete(pathId);
                }
                showToast('路径已删除', 'success');
                console.log(`[GIS] 路径已删除: ${pathId}`);
                
                // 刷新列表
                if (typeof refreshGISPanel === 'function') {
                    refreshGISPanel();
                }
            } else {
                showToast('删除失败', 'danger');
            }
        })
        .catch(e => {
            console.error('[GIS] 删除失败:', e);
            showToast('删除失败', 'danger');
        });
}

// 查看地块
function viewField(id) {
    const fieldId = `FIELD-A0${id}`;
    
    // 从后端获取地块数据
    fetch('/api/gis/fields')
        .then(r => r.json())
        .then(data => {
            const field = data.fields.find(f => f.id === fieldId);
            if (!field) {
                showToast('地块数据未找到', 'warning');
                return;
            }
            
            // 定位到地块
            if (gisMap && field.center) {
                gisMap.setView(field.center, 16);
                
                // 高亮地块
                const layer = fieldLayers[fieldId];
                if (layer) {
                    layer.setStyle({ weight: 4, fillOpacity: 0.3 });
                    layer.openPopup();
                    setTimeout(() => {
                        layer.setStyle({ weight: 2, fillOpacity: 0.15 });
                    }, 3000);
                }
            }
            
            showViewFieldModal(field);
        })
        .catch(e => {
            console.error('[GIS] 加载地块失败:', e);
            showToast('加载地块数据失败', 'danger');
        });
}

function showViewFieldModal(field) {
    const coord = `${field.center[1].toFixed(5)}, ${field.center[0].toFixed(5)}`;
    const boundaryCount = field.boundary ? field.boundary.length : 4;
    const perimeter = boundaryCount > 0 ? (field.area * 28.5).toFixed(1) : '0';
    
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <div>
                    <div style="color: #27ae60; font-size: 24px; font-weight: 700;">${field.id}</div>
                    <div style="color: #2c3e50; font-size: 16px; margin-top: 5px;">${field.name}</div>
                </div>
                <div style="text-align: right;">
                    <div style="color: #7f8c8d; font-size: 12px;">地块面积</div>
                    <div style="color: #f39c12; font-size: 28px; font-weight: 700;">${field.area} <span style="font-size: 14px;">亩</span></div>
                </div>
            </div>
            
            <table style="width: 100%; border-collapse: collapse;">
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 12px; color: #7f8c8d; width: 150px;">中心坐标</td>
                    <td style="padding: 12px; font-family: monospace; color: #3498db; font-weight: 600;">${coord}</td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 12px; color: #7f8c8d;">作业进度</td>
                    <td style="padding: 12px;">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <div style="flex: 1; background: #ecf0f1; height: 8px; border-radius: 4px; overflow: hidden;">
                                <div style="background: ${field.progress === 100 ? '#27ae60' : '#3498db'}; height: 100%; width: ${field.progress}%;"></div>
                            </div>
                            <span style="color: ${field.progress === 100 ? '#27ae60' : '#3498db'}; font-weight: 600; min-width: 40px;">${field.progress}%</span>
                        </div>
                    </td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 12px; color: #7f8c8d;">边界点数</td>
                    <td style="padding: 12px; color: #2c3e50; font-weight: 600;">${boundaryCount} 个</td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 12px; color: #7f8c8d;">周长</td>
                    <td style="padding: 12px; color: #27ae60; font-weight: 600;">${perimeter} m</td>
                </tr>
                <tr>
                    <td style="padding: 12px; color: #7f8c8d;">上次作业</td>
                    <td style="padding: 12px; color: #2c3e50; font-weight: 600;">${field.last_work || '未开始'}</td>
                </tr>
            </table>
        </div>
        
        <div style="background: #e8f5e9; padding: 15px; border-radius: 6px; border-left: 4px solid #27ae60; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #27ae60; margin-bottom: 8px;">作业统计</div>
            <div style="color: #2c3e50; font-size: 13px; line-height: 2;">
                已完成面积: <span style="font-weight: 600;">${(field.area * field.progress / 100).toFixed(1)} 亩</span><br>
                剩余面积: <span style="font-weight: 600;">${(field.area * (100 - field.progress) / 100).toFixed(1)} 亩</span><br>
                预计剩余时间: <span style="font-weight: 600;">${field.progress === 100 ? '已完成' : Math.round((100 - field.progress) * 2.5) + ' 分钟'}</span>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="closeModal()">关闭</button>
        </div>
    `;
    
    showModal('地块详情 - ' + field.name, html);
}

function showOnMap() { showToast('地块边界已显示在地图上', 'success'); }
function generateFieldPath() { showToast('正在为地块生成作业路径', 'info'); }

// 编辑地块
function editField(id) {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">地块信息编辑</div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">地块编号</label>
                <input type="text" value="FIELD-A0${id}" disabled style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: #ecf0f1;">
            </div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">地块名称</label>
                <input type="text" value="东区甘蔗地A" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
            </div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">地块类型</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option>甘蔗种植区</option>
                    <option>试验田</option>
                    <option>育苗区</option>
                    <option>休耕区</option>
                </select>
            </div>
            
            <div>
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">边界调整</label>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                    <button class="btn btn-primary" onclick="redrawBoundary()">重绘边界</button>
                    <button class="btn btn-default" onclick="adjustBoundary()">微调边界</button>
                    <button class="btn btn-warning" onclick="importBoundary()">导入边界</button>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="saveFieldEdit()">保存修改</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('编辑地块信息', html);
}

function redrawBoundary() { showToast('进入边界重绘模式', 'info'); }
function adjustBoundary() { showToast('进入边界微调模式', 'info'); }
function importBoundary() { showToast('选择边界文件导入', 'info'); }
function saveFieldEdit() { showToast('地块信息已保存', 'success'); closeModal(); }

// 导入GIS数据
function importGISData() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">选择导入数据类型</div>
            
            <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px; margin-bottom: 20px;">
                <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #3498db; cursor: pointer;" onclick="selectImportType('path')">
                    <div style="color: #3498db; font-weight: 600; margin-bottom: 8px; font-size: 14px;">作业路径</div>
                    <div style="color: #7f8c8d; font-size: 12px;">支持 GPX, KML, GeoJSON</div>
                </div>
                <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #27ae60; cursor: pointer;" onclick="selectImportType('field')">
                    <div style="color: #27ae60; font-weight: 600; margin-bottom: 8px; font-size: 14px;">地块边界</div>
                    <div style="color: #7f8c8d; font-size: 12px;">支持 SHP, KML, GeoJSON</div>
                </div>
                <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #f39c12; cursor: pointer;" onclick="selectImportType('waypoint')">
                    <div style="color: #f39c12; font-weight: 600; margin-bottom: 8px; font-size: 14px;">路径点位</div>
                    <div style="color: #7f8c8d; font-size: 12px;">支持 CSV, TXT</div>
                </div>
                <div style="background: white; padding: 15px; border-radius: 6px; border: 2px solid #9b59b6; cursor: pointer;" onclick="selectImportType('satellite')">
                    <div style="color: #9b59b6; font-weight: 600; margin-bottom: 8px; font-size: 14px;">卫星地图</div>
                    <div style="color: #7f8c8d; font-size: 12px;">支持 TIF, IMG</div>
                </div>
            </div>
            
            <div style="background: white; padding: 15px; border-radius: 6px; border: 2px dashed #bdc3c7; text-align: center;">
                <div style="color: #7f8c8d; font-size: 14px; margin-bottom: 10px;">拖拽文件到此处或点击选择文件</div>
                <button class="btn btn-primary" onclick="selectFile()">选择文件</button>
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 12px; border-radius: 6px; border-left: 4px solid #f39c12;">
            <div style="color: #856404; font-size: 13px;">
                <strong>注意:</strong> 导入的坐标数据必须与当前坐标系统一致 (WGS-84)，否则可能导致位置偏差。
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="confirmImport()">开始导入</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('导入GIS数据', html);
}

function selectImportType(type) { 
    const types = { path: '作业路径', field: '地块边界', waypoint: '路径点位', satellite: '卫星地图' };
    showToast(`已选择类型: ${types[type]}`, 'info'); 
}
function selectFile() { showToast('打开文件选择对话框', 'info'); }
function confirmImport() { showToast('数据导入成功', 'success'); closeModal(); }

// 导出GIS数据
function exportGISData() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">选择导出内容</div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 10px; font-size: 13px;">数据类型</label>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" checked style="margin-right: 8px;"> 作业路径 (3条)
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" checked style="margin-right: 8px;"> 地块边界 (3个)
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" style="margin-right: 8px;"> GPS轨迹
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" style="margin-right: 8px;"> 作业记录
                    </label>
                </div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 10px; font-size: 13px;">导出格式</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option>GeoJSON (推荐)</option>
                    <option>KML (Google Earth)</option>
                    <option>GPX (GPS设备)</option>
                    <option>Shapefile (ArcGIS)</option>
                    <option>CSV (坐标表)</option>
                </select>
            </div>
            
            <div>
                <label style="display: block; color: #7f8c8d; margin-bottom: 10px; font-size: 13px;">坐标系统</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option>WGS-84 (GPS坐标)</option>
                    <option>GCJ-02 (国测局坐标)</option>
                    <option>BD-09 (百度坐标)</option>
                    <option>UTM Zone 49N</option>
                </select>
            </div>
        </div>
        
        <div style="background: #e3f2fd; padding: 12px; border-radius: 6px; border-left: 4px solid #3498db;">
            <div style="color: #2c3e50; font-size: 13px;">
                <strong>预计文件大小:</strong> <span style="color: #3498db; font-weight: 600;">约 3.2 MB</span><br>
                <strong>包含数据:</strong> 路径3条(78点位) + 地块3个(105点位)
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="confirmExportGIS()">立即导出</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('导出GIS数据', html);
}

function confirmExportGIS() {
    showToast('正在导出GIS数据', 'info');
    setTimeout(() => {
        showToast('文件已保存: gis_export_' + new Date().getTime() + '.geojson', 'success');
        closeModal();
    }, 1500);
}

// GIS系统设置
function showGISSettings() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">坐标系统设置</div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">默认坐标系</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option>WGS-84 (世界大地测量系统)</option>
                    <option>GCJ-02 (中国国测局坐标)</option>
                    <option>BD-09 (百度地图坐标)</option>
                </select>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">基准点设置</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <input type="number" placeholder="经度" value="109.16625" step="0.00001" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                    <input type="number" placeholder="纬度" value="23.75680" step="0.00001" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                </div>
                <button class="btn btn-primary" style="width: 100%; margin-top: 10px;" onclick="getCurrentLocation()">使用当前位置</button>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">地图显示设置</label>
                <div style="background: white; padding: 15px; border-radius: 6px; border: 1px solid #e0e0e0;">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                        <span style="color: #7f8c8d; font-size: 13px;">显示路径编号</span>
                        <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                        <span style="color: #7f8c8d; font-size: 13px;">显示地块边界</span>
                        <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                    </div>
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <span style="color: #7f8c8d; font-size: 13px;">显示GPS轨迹</span>
                        <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                    </div>
                </div>
            </div>
            
            <div>
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">地图缓存管理</label>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                    <button class="btn btn-default" onclick="clearMapCache()">清除缓存</button>
                    <button class="btn btn-primary" onclick="downloadMapTiles()">下载离线地图</button>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="saveGISSettings()">保存设置</button>
            <button class="modal-btn btn-warning" onclick="resetGISSettings()">恢复默认</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('GIS系统设置', html);
}

function getCurrentLocation() { showToast('正在获取当前GPS位置', 'info'); }
function clearMapCache() { 
    if (confirm('确定清除地图缓存？离线地图数据将被删除。')) {
        showToast('地图缓存已清除', 'success'); 
    }
}
function downloadMapTiles() { showToast('开始下载离线地图瓦片', 'info'); }
function saveGISSettings() { showToast('GIS设置已保存', 'success'); closeModal(); }
function resetGISSettings() { showToast('已恢复默认设置', 'info'); }

// GIS地图控制函数（这些会被index.html中的实际函数覆盖）
function selectRobotPath(id) { 
    const robots = ['GZJY001', 'GZJY002'];
    showToast(`切换到${robots[id-1]}机器人路径`, 'info'); 
    return false;
}
function selectTask(id) { 
    showToast(`查看任务A00${id}详情`, 'info'); 
    return false;
}

// GIS更多选项菜单
function showGISMenu() {
    const html = `
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 15px;">
            <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; border: 2px solid #3498db; cursor: pointer;" onclick="managePathList()">
                <div style="text-align: center; margin-bottom: 12px;">
                    <div style="width: 60px; height: 60px; margin: 0 auto; background: #3498db; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 28px; font-weight: 700;">路</div>
                </div>
                <div style="text-align: center; color: #2c3e50; font-weight: 600; margin-bottom: 5px;">路径管理</div>
                <div style="text-align: center; color: #7f8c8d; font-size: 12px;">查看、编辑、删除路径</div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; border: 2px solid #27ae60; cursor: pointer;" onclick="manageFieldList()">
                <div style="text-align: center; margin-bottom: 12px;">
                    <div style="width: 60px; height: 60px; margin: 0 auto; background: #27ae60; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 28px; font-weight: 700;">地</div>
                </div>
                <div style="text-align: center; color: #2c3e50; font-weight: 600; margin-bottom: 5px;">地块管理</div>
                <div style="text-align: center; color: #7f8c8d; font-size: 12px;">地块信息、边界设置</div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; border: 2px solid #f39c12; cursor: pointer;" onclick="importGISData()">
                <div style="text-align: center; margin-bottom: 12px;">
                    <div style="width: 60px; height: 60px; margin: 0 auto; background: #f39c12; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 28px; font-weight: 700;">导</div>
                </div>
                <div style="text-align: center; color: #2c3e50; font-weight: 600; margin-bottom: 5px;">数据导入</div>
                <div style="text-align: center; color: #7f8c8d; font-size: 12px;">导入路径、地块数据</div>
            </div>
            
            <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; border: 2px solid #9b59b6; cursor: pointer;" onclick="showGISSettings()">
                <div style="text-align: center; margin-bottom: 12px;">
                    <div style="width: 60px; height: 60px; margin: 0 auto; background: #9b59b6; border-radius: 50%; display: flex; align-items: center; justify-content: center; color: white; font-size: 28px; font-weight: 700;">设</div>
                </div>
                <div style="text-align: center; color: #2c3e50; font-weight: 600; margin-bottom: 5px;">系统设置</div>
                <div style="text-align: center; color: #7f8c8d; font-size: 12px;">坐标系统、地图配置</div>
            </div>
        </div>
        
        <div class="modal-buttons" style="margin-top: 20px;">
            <button class="modal-btn btn-default" onclick="closeModal()">关闭</button>
        </div>
    `;
    
    showModal('GIS功能菜单', html);
}

function managePathList() {
    closeModal();
    setTimeout(() => createNewPath(), 300);
}

function manageFieldList() {
    closeModal();
    setTimeout(() => viewField(1), 300);
}

function drawPath() {
    // 检查是否已加载地图
    if (!currentMapId) {
        showToast('请先点击"获取地图"选择一个作业地图', 'warning');
        return;
    }
    
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">路径绘制配置</div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">路径名称</label>
                <input type="text" id="path-name-input" placeholder="例如：东区4号作业线" value="东区4号作业线" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 10px; font-size: 13px;">路径类型</label>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                    <label style="display: flex; align-items: center; padding: 12px; background: white; border-radius: 4px; border: 2px solid #e0e0e0; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.borderColor='#3498db'" onmouseout="this.style.borderColor='#e0e0e0'">
                        <input type="radio" name="path-type" value="直线型" checked style="margin-right: 10px; width: 16px; height: 16px;">
                        <span style="font-size: 13px; color: #2c3e50;">直线型（平行作业）</span>
                    </label>
                    <label style="display: flex; align-items: center; padding: 12px; background: white; border-radius: 4px; border: 2px solid #e0e0e0; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.borderColor='#3498db'" onmouseout="this.style.borderColor='#e0e0e0'">
                        <input type="radio" name="path-type" value="曲线型" style="margin-right: 10px; width: 16px; height: 16px;">
                        <span style="font-size: 13px; color: #2c3e50;">曲线型（跟随地形）</span>
                    </label>
                    <label style="display: flex; align-items: center; padding: 12px; background: white; border-radius: 4px; border: 2px solid #e0e0e0; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.borderColor='#3498db'" onmouseout="this.style.borderColor='#e0e0e0'">
                        <input type="radio" name="path-type" value="U型" style="margin-right: 10px; width: 16px; height: 16px;">
                        <span style="font-size: 13px; color: #2c3e50;">U型（田头掉头）</span>
                    </label>
                    <label style="display: flex; align-items: center; padding: 12px; background: white; border-radius: 4px; border: 2px solid #e0e0e0; cursor: pointer; transition: all 0.2s;" onmouseover="this.style.borderColor='#3498db'" onmouseout="this.style.borderColor='#e0e0e0'">
                        <input type="radio" name="path-type" value="环形" style="margin-right: 10px; width: 16px; height: 16px;">
                        <span style="font-size: 13px; color: #2c3e50;">环形（围绕作业）</span>
                    </label>
                </div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">绘制方式</label>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                    <button style="padding: 12px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; font-weight: 600;" onclick="startManualDraw()">手动点击</button>
                    <button style="padding: 12px; background: #27ae60; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; font-weight: 600;" onclick="startRecordDraw()">GPS记录</button>
                    <button style="padding: 12px; background: #95a5a6; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 13px; font-weight: 600;" onclick="importDrawData()">导入坐标</button>
                </div>
            </div>
        </div>
        
        <div style="background: #e3f2fd; padding: 15px; border-radius: 6px; border-left: 4px solid #3498db; margin-bottom: 15px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 8px;">绘制说明</div>
            <div style="color: #2c3e50; font-size: 13px; line-height: 1.8;">
                <strong>手动点击：</strong>在地图上依次点击设置路径点，适合预先规划<br>
                <strong>GPS记录：</strong>机器人实际行走，自动记录GPS轨迹为路径<br>
                <strong>导入坐标：</strong>从CSV或GPX文件导入经纬度坐标
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 12px; border-radius: 6px; border-left: 4px solid #f39c12;">
            <div style="color: #856404; font-size: 13px;">
                <strong>提示：</strong>手动绘制时，在地图上点击添加点位。完成后点击"完成绘制"保存路径。
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('绘制作业路径', html);
}

// startManualDraw 函数已移至 index.html，此处注释掉避免覆盖
// function startManualDraw() { 
//     const pathName = document.getElementById('path-name-input')?.value || '新建路径';
//     
//     // 关闭配置弹窗
//     closeModal();
//     
//     // 启动绘制模式
//     setTimeout(() => {
//         startDrawingMode(pathName);
//         showToast('绘制模式已启动，在地图上点击添加路径点', 'success');
//     }, 300);
// }

function completeDrawing(pathName) {
    finishDrawing(pathName);
}

function startRecordDraw() { 
    const pathName = document.getElementById('path-name-input')?.value || 'GPS记录路径';
    closeModal();
    
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #27ae60; font-size: 18px; margin-top: 15px;">GPS轨迹记录中</h3>
        </div>
        
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 15px;">
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; text-align: center;">
                <div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">记录点数</div>
                    <div style="color: #3498db; font-size: 28px; font-weight: 700;" id="record-count">0</div>
                </div>
                <div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">记录时长</div>
                    <div style="color: #27ae60; font-size: 28px; font-weight: 700;" id="record-time">0</div>
                </div>
                <div>
                    <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">GPS状态</div>
                    <div style="color: #f39c12; font-size: 14px; font-weight: 700; margin-top: 8px;" id="record-gps">等待定位</div>
                </div>
            </div>
        </div>
        
        <div class="log-panel" id="record-log" style="margin-bottom: 15px;"></div>
        
        <div style="background: #e8f5e9; padding: 12px; border-radius: 6px; border-left: 4px solid #27ae60;">
            <div style="color: #27ae60; font-size: 13px;">
                <strong>说明：</strong>机器人行走过程中，系统自动记录GPS位置点生成路径。建议以1-2m/s速度匀速行走。
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="saveGPSRecord('${pathName}')">保存路径</button>
            <button class="modal-btn btn-danger" onclick="stopGPSRecord()">停止记录</button>
        </div>
    `;
    
    showModal('GPS轨迹记录', html);
    startGPSRecording();
}

let gpsRecordTimer = null;
let gpsRecordPoints = [];
let gpsRecordStartTime = null;

function startGPSRecording() {
    gpsRecordPoints = [];
    gpsRecordStartTime = Date.now();
    const logEl = document.getElementById('record-log');
    
    logEl.innerHTML += '<div class="log-line">[启动] GPS轨迹记录已开始</div>';
    
    gpsRecordTimer = setInterval(() => {
        fetch('/api/gps').then(r => r.json()).then(data => {
            if (data.connected && data.latitude != 0) {
                gpsRecordPoints.push([data.latitude, data.longitude]);
                
                document.getElementById('record-count').textContent = gpsRecordPoints.length;
                document.getElementById('record-time').textContent = Math.floor((Date.now() - gpsRecordStartTime) / 1000) + 's';
                document.getElementById('record-gps').textContent = `${data.satellites}颗卫星 ${data.fix_type}`;
                
                if (gpsRecordPoints.length % 10 === 0) {
                    logEl.innerHTML += `<div class="log-line">[记录] 已记录 ${gpsRecordPoints.length} 个GPS点</div>`;
                    logEl.scrollTop = logEl.scrollHeight;
                }
            }
        });
    }, 1000);
}

function saveGPSRecord(pathName) {
    if (gpsRecordTimer) clearInterval(gpsRecordTimer);
    
    if (gpsRecordPoints.length < 2) {
        showToast('记录点位不足，请至少记录2个点', 'warning');
        return;
    }
    
    // 保存到drawnPaths
    const pathId = 'PATH-' + String(Object.keys(drawnPaths).length + 4).padStart(3, '0');
    drawnPaths[pathId] = {
        name: pathName,
        points: gpsRecordPoints,
        created: new Date().toISOString(),
        type: 'GPS记录'
    };
    
    showToast(`GPS路径已保存: ${pathName} (${gpsRecordPoints.length}点)`, 'success');
    console.log('[GPS记录] 保存路径:', drawnPaths[pathId]);
    closeModal();
}

function stopGPSRecord() {
    if (gpsRecordTimer) clearInterval(gpsRecordTimer);
    showToast('GPS记录已停止', 'warning');
    closeModal();
}

function importDrawData() { showToast('选择坐标文件导入', 'info'); }
function confirmDrawPath() { showToast('路径绘制已启动', 'success'); closeModal(); }
function savePath() { showToast('路径已保存', 'success'); closeModal(); }
function testPath() { showToast('开始路径测试', 'info'); }

function autoPlanning() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">AI智能规划参数</div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">选择地块</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option>FIELD-A01 东区甘蔗地A (45.8亩)</option>
                    <option>FIELD-B02 西区甘蔗地B (38.2亩)</option>
                    <option>FIELD-C03 南区甘蔗地C (52.6亩)</option>
                </select>
        </div>
        
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">作业模式</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option>平行往返式（推荐）</option>
                    <option>螺旋式</option>
                    <option>分区式</option>
                    <option>自适应混合</option>
                </select>
            </div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">行距: <span id="row-spacing-val">1.2m</span></label>
                <input type="range" min="0.8" max="2.0" step="0.1" value="1.2" style="width: 100%;" oninput="document.getElementById('row-spacing-val').textContent=this.value+'m'">
            </div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">优化目标</label>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="radio" name="optimize" checked style="margin-right: 8px;"> 最短路径
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="radio" name="optimize" style="margin-right: 8px;"> 最少转弯
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="radio" name="optimize" style="margin-right: 8px;"> 能耗最优
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="radio" name="optimize" style="margin-right: 8px;"> 平衡模式
                    </label>
                </div>
            </div>
        </div>
        
        <div class="log-panel" id="plan-log" style="margin-bottom: 15px;"></div>
        
        <div class="modal-progress" style="margin-bottom: 15px;">
            <div class="modal-progress-label">规划进度</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="plan-p" style="width:0%; background: #27ae60;">0%</div>
            </div>
        </div>
        
        <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 15px; margin-bottom: 20px;">
            <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; text-align: center; border: 2px solid #3498db;">
                <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">规划路径数</div>
                <div style="color: #3498db; font-size: 32px; font-weight: 700;" id="path-cnt">0</div>
                <div style="color: #95a5a6; font-size: 11px; margin-top: 5px;">条</div>
            </div>
            <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; text-align: center; border: 2px solid #27ae60;">
                <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">覆盖面积</div>
                <div style="color: #27ae60; font-size: 32px; font-weight: 700;" id="path-area">0</div>
                <div style="color: #95a5a6; font-size: 11px; margin-top: 5px;">亩</div>
            </div>
            <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; text-align: center; border: 2px solid #f39c12;">
                <div style="color: #7f8c8d; font-size: 12px; margin-bottom: 5px;">预计时长</div>
                <div style="color: #f39c12; font-size: 32px; font-weight: 700;" id="path-time">0</div>
                <div style="color: #95a5a6; font-size: 11px; margin-top: 5px;">小时</div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="startAIPlanning()">开始规划</button>
            <button class="modal-btn btn-primary" onclick="applyPlannedPath()">应用路径</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('AI智能路径规划', html);
}
    
function startAIPlanning() {
    const logs = [
        '[初始化] 加载地块边界数据',
        '[分析] 地块形状：矩形 45.8亩',
        '[计算] 行距1.2m，需要38条路径',
        '[优化] 减少转弯次数',
        '[生成] 主路径 38条',
        '[生成] 掉头路径 2条',
        '[验证] 路径覆盖率 98.5%',
        '[计算] 预计作业时间 3.2小时',
        '[完成] 路径规划完成'
    ];
    
    let idx = 0;
    const logEl = document.getElementById('plan-log');
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            
            const pct = Math.round((idx/logs.length)*100);
            document.getElementById('plan-p').style.width = pct + '%';
            document.getElementById('plan-p').textContent = pct + '%';
            
            if (idx === 4) document.getElementById('path-cnt').textContent = '38';
            if (idx === 6) document.getElementById('path-area').textContent = '45.1';
            if (idx === 7) document.getElementById('path-time').textContent = '3.2';
            
            idx++;
        } else {
            clearInterval(timer);
            showToast('AI路径规划完成', 'success');
        }
    }, 400);
}

function applyPlannedPath() { showToast('规划路径已应用到地图', 'success'); closeModal(); }
function applyPath() { showToast('路径已应用', 'success'); closeModal(); }
function regenPath() { autoPlanning(); }

function exportPath() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">路径导出配置</div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">选择路径</label>
                <select id="export-path-select" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option value="1">PATH-001 东区1号作业线 (24点)</option>
                    <option value="2">PATH-002 西区2号作业线 (36点)</option>
                    <option value="3">PATH-003 南区掉头路径 (18点)</option>
                    <option value="all">全部路径 (78点)</option>
                </select>
            </div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">导出格式</label>
                <select id="export-format-select" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option value="geojson">GeoJSON (推荐，Web GIS标准)</option>
                    <option value="kml">KML (Google Earth)</option>
                    <option value="gpx">GPX (GPS设备通用)</option>
                    <option value="csv">CSV (坐标表格)</option>
                    <option value="shp">Shapefile (ArcGIS)</option>
                </select>
                </div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">坐标系统</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option>WGS-84 (GPS原始坐标)</option>
                    <option>GCJ-02 (国测局坐标)</option>
                    <option>BD-09 (百度地图坐标)</option>
                    <option>UTM Zone 49N (投影坐标)</option>
                </select>
            </div>
            
            <div>
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">附加信息</label>
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px;">
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" checked style="margin-right: 8px;"> 时间戳
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" checked style="margin-right: 8px;"> 海拔高度
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" style="margin-right: 8px;"> 路径属性
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" style="margin-right: 8px;"> 作业记录
                    </label>
                </div>
            </div>
        </div>
        
        <div style="background: #1e1e1e; color: #00ff00; padding: 15px; border-radius: 6px; font-family: 'Courier New', monospace; font-size: 11px; max-height: 180px; overflow-y: auto; margin-bottom: 15px;">
            <div>// 路径数据预览 (GeoJSON格式)</div>
                <div>{</div>
            <div>  "type": "FeatureCollection",</div>
            <div>  "features": [{</div>
            <div>    "type": "Feature",</div>
            <div>    "properties": {</div>
            <div>      "name": "东区1号作业线",</div>
            <div>      "path_id": "PATH-001",</div>
            <div>      "created": "2024-10-20T09:15:30Z"</div>
            <div>    },</div>
            <div>    "geometry": {</div>
            <div>      "type": "LineString",</div>
            <div>      "coordinates": [</div>
            <div>        [109.16625, 23.75680, 125.5],</div>
            <div>        [109.16638, 23.75692, 125.8],</div>
            <div>        ...</div>
            <div>      ]</div>
            <div>    }</div>
            <div>  }]</div>
                <div>}</div>
        </div>
        
        <div style="background: #e3f2fd; padding: 12px; border-radius: 6px; border-left: 4px solid #3498db;">
            <div style="color: #2c3e50; font-size: 13px;">
                <strong>文件信息:</strong> 预计大小约 2.8 KB，包含 24 个路径点位及属性数据
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="confirmExportPath()">立即导出</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('导出路径数据', html);
}

function confirmExportPath() {
    const selectEl = document.getElementById('export-path-select');
    const formatEl = document.getElementById('export-format-select');
    
    const pathId = selectEl ? selectEl.value : 'all';
    const format = formatEl ? formatEl.value : 'geojson';
    
    // 从后端获取路径数据
    fetch('/api/gis/paths')
        .then(r => r.json())
        .then(data => {
            let pathsToExport = [];
            
            if (pathId === 'all') {
                pathsToExport = data.paths;
            } else {
                const path = data.paths.find(p => p.id === `PATH-00${pathId}`);
                if (path) pathsToExport = [path];
            }
            
            if (pathsToExport.length === 0) {
                showToast('没有可导出的路径', 'warning');
                return;
            }
            
            // 生成GeoJSON格式
            const geojson = {
                type: 'FeatureCollection',
                features: pathsToExport.map(path => ({
                    type: 'Feature',
                    properties: {
                        name: path.name,
                        path_id: path.id,
                        path_type: path.type,
                        created: path.created,
                        status: path.status
                    },
                    geometry: {
                        type: 'LineString',
                        coordinates: path.points.map(p => [p[1], p[0]]) // [lng, lat]
                    }
                }))
            };
            
            // 下载文件
            const blob = new Blob([JSON.stringify(geojson, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `path_export_${new Date().getTime()}.${format}`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showToast(`文件已下载: ${pathsToExport.length}条路径`, 'success');
            console.log('[GIS] 导出数据:', geojson);
            closeModal();
        })
        .catch(e => {
            console.error('[GIS] 导出失败:', e);
            showToast('导出失败', 'danger');
        });
}

function exportFmt(fmt) { showToast(`导出${fmt}格式`, 'info'); }
function downloadPath() { showToast('文件已下载', 'success'); closeModal(); }
function emailPath() { showToast('已发送到邮箱', 'success'); }

function loadGISMap() {
    // 先获取地图列表
    fetch('/api/gis/maps')
        .then(r => r.json())
        .then(data => {
            showMapSelectModal(data.maps || []);
        })
        .catch(e => {
            console.error('[GIS] 加载地图列表失败:', e);
            showToast('加载地图列表失败', 'danger');
        });
}

function showMapSelectModal(maps) {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">选择作业地图</div>
            
            <div style="margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">可用地图列表</label>
                <div style="max-height: 300px; overflow-y: auto;">
                    ${maps.map(m => `
                        <div style="background: white; padding: 15px; border-radius: 4px; margin-bottom: 10px; border: 2px solid #e0e0e0; cursor: pointer; transition: all 0.2s;" 
                             onclick="selectMapToLoad('${m.id}')" 
                             onmouseover="this.style.borderColor='#3498db'" 
                             onmouseout="this.style.borderColor='#e0e0e0'">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <div>
                                    <div style="font-weight: 600; color: #2c3e50; font-size: 14px; margin-bottom: 5px;">${m.name}</div>
                                    <div style="font-size: 12px; color: #7f8c8d;">编号: ${m.id} | 创建: ${m.created.split('T')[0]}</div>
                                    <div style="font-size: 11px; color: #95a5a6; margin-top: 3px;">中心: ${m.center[0].toFixed(5)}, ${m.center[1].toFixed(5)}</div>
                                </div>
                                <div style="text-align: right;">
                                    <div style="color: #3498db; font-size: 20px; font-weight: 700;">${m.paths ? m.paths.length : 0}</div>
                                    <div style="font-size: 11px; color: #7f8c8d;">条路径</div>
                                </div>
                            </div>
                        </div>
                    `).join('')}
                </div>
            </div>
        </div>
        
        <div style="background: #e3f2fd; padding: 12px; border-radius: 6px; border-left: 4px solid #3498db;">
            <div style="color: #2c3e50; font-size: 13px;">
                <strong>说明：</strong>选择地图后将加载该地图及其所有已绘制的路径
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('选择作业地图', html);
}

function selectMapToLoad(mapId) {
    closeModal();
    
    // 显示加载进度
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #3498db; font-size: 18px; margin-top: 15px;">正在加载地图</h3>
            </div>
        
        <div class="log-panel" id="map-load-log" style="margin-bottom: 15px;"></div>
        
        <div class="modal-progress">
            <div class="modal-progress-label">加载进度</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="map-load-p" style="width:0%; background: #3498db;">0%</div>
            </div>
        </div>
    `;
    
    showModal('加载地图中', html);
    
    const logs = [
        `[加载] 地图 ${mapId}`,
        '[初始化] Leaflet地图引擎',
        '[渲染] 地图图层',
        '[读取] 路径数据',
        '[显示] 路径到地图',
        '[完成] 地图加载成功'
    ];
    
    let idx = 0;
    const logEl = document.getElementById('map-load-log');
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            
            const pct = Math.round((idx/logs.length)*100);
            document.getElementById('map-load-p').style.width = pct + '%';
            document.getElementById('map-load-p').textContent = pct + '%';
            
            idx++;
        } else {
            clearInterval(timer);
            
            // 实际加载地图和路径
            actualLoadMap(mapId);
        }
    }, 300);
}

function actualLoadMap(mapId) {
    currentMapId = mapId;
    
    // 初始化地图（如果还没初始化）
    if (!gisMap) {
        initGISMap();
    }
    
    // 加载该地图的路径
    fetch(`/api/gis/map/${mapId}/paths`)
        .then(r => r.json())
        .then(data => {
            currentMapData = data;
            const paths = data.paths || [];
            
            // 清除现有图层
            Object.values(pathLayers).forEach(layer => {
                if (gisMap) gisMap.removeLayer(layer);
            });
            pathLayers = {};
            
            // 显示新路径
            if (paths.length > 0) {
                paths.forEach(path => {
                    displayPathOnMap(path);
                });
                
                // 定位到第一条路径
                const firstPath = paths[0];
                if (firstPath.points && firstPath.points.length > 0) {
                    const bounds = L.latLngBounds(firstPath.points);
                    gisMap.fitBounds(bounds, { padding: [50, 50] });
                }
            }
            
            // 更新左侧列表
            const pathListHtml = paths.map((path, i) => {
                const colors = ['#3498db', '#27ae60', '#f39c12'];
                const color = colors[i % 3];
                const statusBadge = path.status === '已验证' ? 
                    '<span class="badge badge-success" style="font-size: 10px;">已验证</span>' :
                    '<span class="badge badge-warning" style="font-size: 10px;">待验证</span>';
                
                return `
                    <div style="background: #f8f9fa; padding: 10px; border-radius: 4px; margin-bottom: 6px; border-left: 3px solid ${color}; position: relative;">
                        <div style="cursor: pointer;" onclick="loadPathById('${path.id}')">
                            <div style="font-weight: 600; color: #2c3e50; font-size: 13px; margin-bottom: 3px;">${path.id}</div>
                            <div style="font-size: 11px; color: #7f8c8d;">${path.name} | ${path.point_count}点 | ${path.length}m</div>
                            <div style="margin-top: 5px;">${statusBadge}</div>
                        </div>
                        <button onclick="deletePathFromMap('${path.id}'); event.stopPropagation();" style="position: absolute; top: 8px; right: 8px; padding: 4px 10px; background: #e74c3c; color: white; border: none; border-radius: 3px; cursor: pointer; font-size: 11px; font-weight: 600;">删除</button>
                    </div>
                `;
            }).join('');
            
            const listContainer = document.getElementById('gis-path-list');
            const countEl = document.getElementById('gis-path-count');
            
            if (listContainer) {
                listContainer.innerHTML = pathListHtml || '<div style="color: #7f8c8d; padding: 15px; text-align: center; font-size: 12px;">暂无路径</div>';
            }
            
            if (countEl) {
                countEl.textContent = paths.length;
            }
            
            // 更新底部信息
            document.getElementById('map-create-date').textContent = new Date().toISOString().split('T')[0];
            document.getElementById('map-creator').textContent = mapId;
            document.getElementById('map-location').textContent = data.map_name || mapId;
            
            showToast(`地图加载完成: ${data.map_name || mapId}，${paths.length} 条路径`, 'success');
            closeModal();
        })
        .catch(e => {
            console.error('[GIS] 加载地图路径失败:', e);
            showToast('加载地图失败', 'danger');
            closeModal();
        });
}


// ========== 页面5: 通讯模块按钮 ==========

function testConnection() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #3498db; font-size: 16px;">网络连接测试</h3>
        </div>
        
        <div class="log-panel" id="conn-log"></div>
        
        <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-top: 20px;">
            <h4 style="color: #2c3e50; margin-bottom: 12px;">测试结果</h4>
            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                <span style="color: #7f8c8d;">TCP/IP</span>
                <span class="badge badge-success" id="tcp-test">测试中</span>
            </div>
            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                <span style="color: #7f8c8d;">Modbus</span>
                <span class="badge badge-success" id="modbus-test">测试中</span>
            </div>
            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                <span style="color: #7f8c8d;">GPS</span>
                <span class="badge badge-success" id="gps-test">测试中</span>
            </div>
            <div style="display: flex; justify-content: space-between;">
                <span style="color: #7f8c8d;">雷达</span>
                <span class="badge badge-success" id="lidar-test">测试中</span>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="closeModal()">关闭</button>
        </div>
    `;
    
    showModal('网络连接测试', html);
    
    const logs = [
        '[Ping] 192.168.10.100 延迟3ms',
        '[TCP] 端口9000 OK',
        '[TCP] 端口9001 OK',
        '[TCP] 端口9002 OK',
        '[Modbus] 读寄存器0x129 OK',
        '[GPS] NMEA数据 OK',
        '[雷达] 点云数据 OK',
        '[完成] 所有测试通过'
    ];
    
    let idx = 0;
    const logEl = document.getElementById('conn-log');
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            
            if (idx === 3) document.getElementById('tcp-test').textContent = 'OK';
            if (idx === 4) document.getElementById('modbus-test').textContent = 'OK';
            if (idx === 5) document.getElementById('gps-test').textContent = 'OK';
            if (idx === 6) document.getElementById('lidar-test').textContent = 'OK';
            
            idx++;
        } else {
            clearInterval(timer);
            showToast('连接测试完成', 'success');
        }
    }, 400);
}

function restartModbus() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #f39c12; font-size: 16px;">重启Modbus服务</h3>
        </div>
        
        <div class="log-panel" id="modbus-log"></div>
        
        <div class="modal-progress">
            <div class="modal-progress-label">重启进度</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="modbus-p" style="width:0%; background: #f39c12;">0%</div>
            </div>
        </div>
    `;
    
    showModal('重启Modbus', html);
    
    const logs = [
        '[停止] Modbus服务',
        '[清理] 释放/dev/ttyUSB0',
        '[清理] 清除缓存',
        '[等待] 3秒',
        '[启动] 初始化客户端',
        '[连接] PLC (Slave 1)',
        '[测试] 读寄存器',
        '[测试] 写寄存器',
        '[完成] 重启成功'
    ];
    
    animateProgress(logs, ['modbus-p'], 'modbus-log', () => {
        setTimeout(() => {
            showToast('Modbus已重启', 'success');
            closeModal();
        }, 800);
    });
}

function showCommLog() {
    const html = `
        <div style="margin-bottom: 15px;">
            <div style="display: flex; gap: 10px;">
                <button class="btn btn-primary" onclick="filterLog('all')">全部</button>
                <button class="btn btn-default" onclick="filterLog('tcp')">TCP</button>
                <button class="btn btn-default" onclick="filterLog('modbus')">Modbus</button>
                <button class="btn btn-danger" onclick="filterLog('error')">错误</button>
            </div>
        </div>
        
        <div class="log-panel" style="height: 350px;">
            <div class="log-line">[10:25:30] [TCP] 连接: 192.168.10.100:9000</div>
            <div class="log-line">[10:25:31] [Modbus] 读寄存器129: 24850</div>
            <div class="log-line">[10:25:32] [GPS] 接收GNGGA</div>
            <div class="log-line">[10:25:33] [雷达] 点云325点</div>
            <div class="log-line">[10:25:34] [TCP] 控制命令: forward=15</div>
            <div class="log-line">[10:25:35] [Modbus] 写寄存器122: 15</div>
            <div class="log-line">[10:25:36] [GPS] 8颗卫星</div>
            <div class="log-line">[10:25:37] [雷达] 障碍物2.3m</div>
            <div class="log-line">[10:25:38] [TCP] 状态确认</div>
            <div class="log-line">[10:25:39] [系统] 通讯正常</div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="exportLog()">导出日志</button>
            <button class="modal-btn btn-danger" onclick="clearLog()">清空日志</button>
        </div>
    `;
    
    showModal('通讯日志', html);
}

function filterLog(type) { showToast(`筛选${type}日志`, 'info'); }
function exportLog() { showToast('日志已导出', 'success'); }
function clearLog() { showToast('日志已清空', 'warning'); }

function diagNetwork() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #3498db; font-size: 16px;">网络诊断</h3>
        </div>
        
        <div class="log-panel" id="diag-log"></div>
        
        <div class="modal-grid">
            <div class="modal-card">
                <div class="modal-card-label">网络延迟</div>
                <div class="modal-card-value" style="font-size: 28px;" id="latency">0</div>
                <div class="modal-card-unit">ms</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">丢包率</div>
                <div class="modal-card-value" style="font-size: 28px;" id="loss">0</div>
                <div class="modal-card-unit">%</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">带宽</div>
                <div class="modal-card-value" style="font-size: 28px;" id="bandwidth">0</div>
                <div class="modal-card-unit">Mbps</div>
            </div>
        </div>
    `;
    
    showModal('网络诊断工具', html);
    
    const logs = [
        '[Ping] 测试延迟',
        '[Ping] 平均3.2ms',
        '[测试] 丢包(100包)',
        '[测试] 丢包率0%',
        '[测试] 带宽',
        '[测试] 上行95.3Mbps',
        '[测试] 下行97.8Mbps',
        '[完成] 网络状态良好'
    ];
    
    let idx = 0;
    const logEl = document.getElementById('diag-log');
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            
            if (idx === 1) document.getElementById('latency').textContent = '3.2';
            if (idx === 3) document.getElementById('loss').textContent = '0.0';
            if (idx === 6) document.getElementById('bandwidth').textContent = '95.3';
            
            idx++;
        } else {
            clearInterval(timer);
        }
    }, 400);
}

function setCommParams() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px;">
            <div style="margin-bottom: 15px;">
                <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">服务器IP地址</label>
                <input type="text" value="192.168.10.1" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
            </div>
            <div style="margin-bottom: 15px;">
                <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">TCP端口配置</label>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                    <input type="number" value="9000" placeholder="控制" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                    <input type="number" value="9001" placeholder="雷达" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                    <input type="number" value="9002" placeholder="GPS" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                </div>
            </div>
            <div style="margin-bottom: 15px;">
                <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">Modbus波特率</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                    <option>9600</option>
                    <option>19200</option>
                    <option>38400</option>
                    <option>115200</option>
                </select>
            </div>
            <div>
                <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">连接超时(秒)</label>
                <input type="number" value="10" min="5" max="60" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="saveParams()">保存配置</button>
            <button class="modal-btn btn-primary" onclick="testParams()">测试连接</button>
        </div>
    `;
    
    showModal('通讯参数设置', html);
}

function saveParams() { showToast('参数已保存', 'success'); closeModal(); }
function testParams() { testConnection(); }

// ========== 页面6: 信息管理按钮 ==========

function exportDataReport() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 20px;">
            <div style="margin-bottom: 15px;">
                <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">报表类型</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                    <option>作业统计报表</option>
                    <option>设备运行报表</option>
                    <option>故障记录报表</option>
                    <option>维护保养报表</option>
                    <option>全部数据</option>
                </select>
            </div>
            <div style="margin-bottom: 15px;">
                <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">时间范围</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <input type="date" value="2024-10-01" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                    <input type="date" value="2024-10-22" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                </div>
            </div>
            <div>
                <label style="color: #7f8c8d; display: block; margin-bottom: 8px;">导出格式</label>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                    <button class="btn btn-primary" onclick="exportRpt('Excel')">Excel</button>
                    <button class="btn btn-primary" onclick="exportRpt('PDF')">PDF</button>
                    <button class="btn btn-primary" onclick="exportRpt('CSV')">CSV</button>
                </div>
            </div>
        </div>
        
        <div class="modal-grid" style="grid-template-columns: repeat(2, 1fr);">
            <div class="modal-card">
                <div class="modal-card-label">记录总数</div>
                <div class="modal-card-value" style="font-size: 28px;">1,245</div>
            </div>
            <div class="modal-card">
                <div class="modal-card-label">文件大小</div>
                <div class="modal-card-value" style="font-size: 28px;">2.8</div>
                <div class="modal-card-unit">MB</div>
            </div>
        </div>
    `;
    
    showModal('导出数据报表', html);
}

function exportRpt(fmt) {
    showToast(`正在导出${fmt}格式`, 'info');
    setTimeout(() => {
        showToast(`${fmt}报表已下载`, 'success');
        closeModal();
    }, 1500);
}

function showDetailRecords() {
    const html = `
        <table class="data-table">
            <thead>
                <tr>
                    <th>时间</th>
                    <th>机器人</th>
                    <th>事件</th>
                    <th>状态</th>
                </tr>
            </thead>
            <tbody>
                ${generateRecords(12)}
            </tbody>
        </table>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="prevPage()">上一页</button>
            <button class="modal-btn btn-primary" onclick="nextPage()">下一页</button>
        </div>
    `;
    
    showModal('详细记录', html);
}

function generateRecords(n) {
    const events = ['GPS定位', '雷达扫描', 'PLC通信', '作业开始', '作业完成'];
    const robots = ['GZJY001', 'GZJY002'];
    let html = '';
    for (let i = 0; i < n; i++) {
        const time = `10:${String(25+i).padStart(2,'0')}:${String(Math.floor(Math.random()*60)).padStart(2,'0')}`;
        const robot = robots[Math.floor(Math.random()*robots.length)];
        const event = events[Math.floor(Math.random()*events.length)];
        html += `
            <tr>
                <td>${time}</td>
                <td>${robot}</td>
                <td>${event}</td>
                <td><span class="badge badge-success">正常</span></td>
            </tr>
        `;
    }
    return html;
}

function prevPage() { showToast('已到第一页', 'warning'); }
function nextPage() { showToast('加载下一页', 'info'); }

// ========== 页面7: 系统服务按钮 ==========

function restartSystemService() {
    const html = `
        <div style="text-align: center; padding: 25px 0;">
            <div style="width: 80px; height: 80px; border-radius: 50%; background: #fdebd0; display: flex; align-items: center; justify-content: center; margin: 0 auto 20px; border: 3px solid #f39c12;">
                <span style="font-size: 40px; color: #f39c12;">!</span>
            </div>
            <h3 style="color: #f39c12; font-size: 18px; margin-bottom: 10px;">确认重启系统服务？</h3>
            <p style="color: #7f8c8d; font-size: 14px;">重启可能导致短暂连接中断</p>
        </div>
        
        <div style="background: #fadbd8; padding: 15px; border-radius: 6px; border-left: 4px solid #e74c3c; margin: 20px 0;">
            <div style="font-weight: 600; color: #c0392b; margin-bottom: 8px;">影响范围</div>
            <div style="color: #7f8c8d; font-size: 13px; line-height: 1.8;">
                • Web服务将重启(约10秒)<br>
                • Socket连接将断开重连<br>
                • 数据接收将暂停
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-warning" onclick="confirmRestart()">确认重启</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('重启系统服务', html);
}

function confirmRestart() {
    showToast('系统服务重启中', 'warning');
    closeModal();
    setTimeout(() => showToast('系统服务已重启', 'success'), 3000);
}

function showSystemLog() {
    const html = `
        <div class="log-panel" style="height: 400px;">
            <div class="log-line">[INFO] Flask application started</div>
            <div class="log-line">[INFO] SocketIO initialized</div>
            <div class="log-line">[INFO] TCP服务器启动: 9000,9001,9002,9003</div>
            <div class="log-line">[INFO] Web服务器: http://192.168.10.1:5000</div>
            <div class="log-line">[INFO] 机器人GZJY001连接</div>
            <div class="log-line">[INFO] GPS数据流建立</div>
            <div class="log-line">[INFO] 雷达数据流建立</div>
            <div class="log-line">[INFO] PLC通信建立</div>
            <div class="log-line">[INFO] 所有服务运行正常</div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="refreshLog()">刷新</button>
            <button class="modal-btn btn-success" onclick="exportSysLog()">导出</button>
        </div>
    `;
    
    showModal('系统日志', html);
}

function refreshLog() { showToast('日志已刷新', 'info'); }
function exportSysLog() { showToast('日志已导出', 'success'); }

function backupData() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #3498db; font-size: 16px;">备份系统数据</h3>
        </div>
        
        <div class="log-panel" id="backup-log"></div>
        
        <div class="modal-progress">
            <div class="modal-progress-label">备份进度</div>
            <div class="modal-progress-bar">
                <div class="modal-progress-fill" id="backup-p" style="width:0%;">0%</div>
            </div>
        </div>
        
        <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-top: 20px;">
            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                <span style="color: #7f8c8d;">备份位置</span>
                <span style="color: #3498db; font-weight: 500;">D:\\Backup\\2024-10-22</span>
            </div>
            <div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
                <span style="color: #7f8c8d;">备份大小</span>
                <span style="color: #27ae60; font-weight: 600;" id="backup-size">0 MB</span>
            </div>
            <div style="display: flex; justify-content: space-between;">
                <span style="color: #7f8c8d;">预计时间</span>
                <span style="color: #f39c12; font-weight: 600;" id="backup-eta">计算中</span>
            </div>
        </div>
    `;
    
    showModal('备份系统数据', html);
    
    const logs = [
        '[备份] 数据库15.3MB',
        '[备份] 配置文件0.5MB',
        '[备份] 日志28.7MB',
        '[备份] GPS数据45.2MB',
        '[压缩] 打包中',
        '[完成] 总大小89.7MB'
    ];
    
    let idx = 0;
    const logEl = document.getElementById('backup-log');
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            
            const pct = Math.round((idx/logs.length)*100);
            document.getElementById('backup-p').style.width = pct + '%';
            document.getElementById('backup-p').textContent = pct + '%';
            
            const size = (idx*15+5).toFixed(1);
            document.getElementById('backup-size').textContent = size + ' MB';
            document.getElementById('backup-eta').textContent = ((logs.length-idx)*2) + '秒';
            
            idx++;
        } else {
            clearInterval(timer);
            setTimeout(() => {
                showToast('备份完成', 'success');
                closeModal();
            }, 800);
        }
    }, 500);
}

function showSystemSettings() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px;">
            <div style="margin-bottom: 20px;">
                <h4 style="color: #2c3e50; font-size: 15px; margin-bottom: 12px;">界面设置</h4>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <span style="color: #7f8c8d;">自动保存状态</span>
                    <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <span style="color: #7f8c8d;">声音提示</span>
                    <div class="switch" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #7f8c8d;">深色模式</span>
                    <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                </div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <h4 style="color: #2c3e50; font-size: 15px; margin-bottom: 12px;">数据设置</h4>
                <div style="margin-bottom: 12px;">
                    <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">数据刷新间隔(秒)</label>
                    <input type="number" value="2" min="1" max="60" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                </div>
                <div>
                    <label style="color: #7f8c8d; display: block; margin-bottom: 5px;">日志保留天数</label>
                    <input type="number" value="30" min="7" max="365" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                </div>
            </div>
            
            <div>
                <h4 style="color: #2c3e50; font-size: 15px; margin-bottom: 12px;">安全设置</h4>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <span style="color: #7f8c8d;">操作确认</span>
                    <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #7f8c8d;">自动备份</span>
                    <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="saveSettings()">保存设置</button>
            <button class="modal-btn btn-warning" onclick="resetSettings()">恢复默认</button>
        </div>
    `;
    
    showModal('系统设置', html);
}

function toggleSwitch(el) {
    el.classList.toggle('on');
    showToast(el.classList.contains('on') ? '已开启' : '已关闭', 'info');
}

function saveSettings() { showToast('设置已保存', 'success'); closeModal(); }
function resetSettings() { showToast('已恢复默认设置', 'warning'); }

function showAboutSystem() {
    const html = `
        <div style="text-align: center; padding: 20px 0;">
            <div style="width: 80px; height: 80px; background: #3498db; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 15px;">
                <span style="font-size: 40px; color: white;">V</span>
            </div>
            <h2 style="color: #2c3e50; font-size: 20px; margin-bottom: 5px;">甘蔗农机智能管控平台</h2>
            <p style="color: #7f8c8d; font-size: 16px; margin-bottom: 25px;">Version 1.0.0</p>
        </div>
        
        <div style="background: #f8f9fa; padding: 20px; border-radius: 6px; margin-bottom: 20px;">
            <div style="margin-bottom: 12px; color: #7f8c8d;">
                <span style="font-weight: 600; color: #2c3e50;">开发团队:</span> 智能农机研发中心
            </div>
            <div style="margin-bottom: 12px; color: #7f8c8d;">
                <span style="font-weight: 600; color: #2c3e50;">技术栈:</span> Python + Flask + RK3588 + Modbus
            </div>
            <div style="margin-bottom: 12px; color: #7f8c8d;">
                <span style="font-weight: 600; color: #2c3e50;">发布日期:</span> 2024年10月
            </div>
            <div style="color: #7f8c8d;">
                <span style="font-weight: 600; color: #2c3e50;">许可证:</span> 企业授权版
            </div>
        </div>
        
        <div style="background: #d5f4e6; padding: 15px; border-radius: 6px; border-left: 4px solid #27ae60;">
            <div style="font-weight: 600; color: #27ae60; margin-bottom: 8px;">系统特性</div>
            <div style="color: #229954; font-size: 13px; line-height: 1.8;">
                • 实时GPS定位与轨迹记录<br>
                • 360度激光雷达环境感知<br>
                • Modbus工业控制总线<br>
                • 多机器人协同作业<br>
                • AI智能路径规划<br>
                • 完整数据统计分析
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-primary" onclick="checkUpdate()">检查更新</button>
            <button class="modal-btn btn-success" onclick="showLicense()">查看许可证</button>
        </div>
    `;
    
    showModal('关于系统', html);
}

function checkUpdate() { showToast('当前已是最新版本', 'success'); }
function showLicense() { showToast('许可证信息已发送到邮箱', 'info'); }

// ========== 辅助函数 ==========

function animateProgress(logs, progressIds, logId, callback) {
    let idx = 0;
    const logEl = document.getElementById(logId);
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            
            progressIds.forEach((pid, i) => {
                const start = Math.floor(logs.length * i / progressIds.length);
                if (idx >= start) {
                    const localProgress = idx - start;
                    const localTotal = Math.floor(logs.length / progressIds.length);
                    const pct = Math.min(100, Math.round((localProgress / localTotal) * 100));
                    const el = document.getElementById(pid);
                    if (el) {
                        el.style.width = pct + '%';
                        el.textContent = pct + '%';
                    }
                }
            });
            
            idx++;
        } else {
            clearInterval(timer);
            if (callback) callback();
        }
    }, 300);
}

// ========== 算法模块主界面按钮 ==========

function startAllAlgorithms() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div class="spinner"></div>
            <h3 style="color: #27ae60; font-size: 18px; margin-top: 15px;">正在启动全部算法模块</h3>
        </div>
        
        <div class="log-panel" id="start-all-log"></div>
        
        <div style="margin-top: 20px;">
            <table style="width: 100%; border-collapse: collapse;">
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 10px; color: #7f8c8d;">甘蔗识别算法</td>
                    <td style="padding: 10px; text-align: right;"><span class="badge badge-success" id="sa1">运行中</span></td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 10px; color: #7f8c8d;">割叶控制算法</td>
                    <td style="padding: 10px; text-align: right;"><span class="badge badge-success" id="sa2">运行中</span></td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 10px; color: #7f8c8d;">甘蔗行识别</td>
                    <td style="padding: 10px; text-align: right;"><span class="badge badge-success" id="sa3">运行中</span></td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 10px; color: #7f8c8d;">障碍物检测</td>
                    <td style="padding: 10px; text-align: right;"><span class="badge badge-success" id="sa4">运行中</span></td>
                </tr>
                <tr style="border-bottom: 1px solid #ecf0f1;">
                    <td style="padding: 10px; color: #7f8c8d;">路径规划</td>
                    <td style="padding: 10px; text-align: right;"><span class="badge badge-success" id="sa5">运行中</span></td>
                </tr>
                <tr>
                    <td style="padding: 10px; color: #7f8c8d;">地形自适应</td>
                    <td style="padding: 10px; text-align: right;"><span class="badge badge-success" id="sa6">运行中</span></td>
                </tr>
            </table>
        </div>
    `;
    
    showModal('启动全部算法', html);
    
    const logs = [
        '[初始化] 加载算法配置文件',
        '[启动] 甘蔗识别算法 - YOLOv8模型',
        '[启动] 割叶控制算法 - PID控制器',
        '[启动] 甘蔗行识别 - 传感器融合',
        '[启动] 障碍物检测 - 激光雷达',
        '[启动] 路径规划 - A*+DWA混合',
        '[启动] 地形自适应 - IMU姿态控制',
        '[完成] 全部算法模块已启动'
    ];
    
    let idx = 0;
    const logEl = document.getElementById('start-all-log');
    const timer = setInterval(() => {
        if (idx < logs.length) {
            logEl.innerHTML += `<div class="log-line">${logs[idx]}</div>`;
            logEl.scrollTop = logEl.scrollHeight;
            idx++;
        } else {
            clearInterval(timer);
            setTimeout(() => {
                // 更新主界面状态
                for (let i = 1; i <= 6; i++) {
                    const el = document.getElementById(`algo-status-${i}`);
                    if (el) {
                        el.textContent = '运行中';
                        el.className = 'badge badge-success';
                    }
                }
                showToast('全部算法已启动', 'success');
                closeModal();
            }, 1000);
        }
    }, 300);
}

function stopAllAlgorithms() {
    if (confirm('确定停止全部算法模块？这将终止所有自动控制功能。')) {
        showToast('正在停止全部算法...', 'warning');
        setTimeout(() => {
            for (let i = 1; i <= 6; i++) {
                const el = document.getElementById(`algo-status-${i}`);
                if (el) {
                    el.textContent = '已停止';
                    el.className = 'badge badge-danger';
                }
            }
            showToast('全部算法已停止', 'warning');
        }, 1500);
    }
}

function showAlgorithmConfig() {
    const html = `
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px;">算法全局配置</div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">算法运行优先级</label>
                <select style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px; background: white;">
                    <option>安全优先（推荐）</option>
                    <option>效率优先</option>
                    <option>精度优先</option>
                    <option>平衡模式</option>
                </select>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">GPU资源分配</label>
                <input type="range" min="40" max="90" value="70" style="width: 100%;" oninput="document.getElementById('gpu-val').textContent=this.value+'%'">
                <div style="text-align: center; margin-top: 5px; color: #3498db; font-weight: 600;"><span id="gpu-val">70%</span></div>
            </div>
            
            <div style="margin-bottom: 20px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">算法更新频率 (Hz)</label>
                <input type="number" value="20" min="10" max="50" style="width: 100%; padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
            </div>
            
            <div style="background: white; padding: 15px; border-radius: 6px; border: 1px solid #e0e0e0;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 12px; font-size: 13px;">高级选项</div>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <span style="color: #7f8c8d; font-size: 13px;">启用日志记录</span>
                    <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                    <span style="color: #7f8c8d; font-size: 13px;">性能监控</span>
                    <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                </div>
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span style="color: #7f8c8d; font-size: 13px;">自动异常恢复</span>
                    <div class="switch on" onclick="toggleSwitch(this)"><div class="switch-handle"></div></div>
                </div>
            </div>
        </div>
        
        <div class="modal-buttons">
            <button class="modal-btn btn-success" onclick="saveAlgoConfig()">保存配置</button>
            <button class="modal-btn btn-warning" onclick="resetAlgoConfig()">恢复默认</button>
            <button class="modal-btn btn-default" onclick="closeModal()">取消</button>
        </div>
    `;
    
    showModal('算法配置', html);
}

function saveAlgoConfig() {
    showToast('算法配置已保存', 'success');
    closeModal();
}

function resetAlgoConfig() {
    showToast('已恢复默认配置', 'info');
}

function exportAlgorithmLog() {
    const html = `
        <div style="margin-bottom: 20px;">
            <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">选择日志类型</label>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" checked style="margin-right: 8px;"> 识别日志
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" checked style="margin-right: 8px;"> 控制日志
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" checked style="margin-right: 8px;"> 性能日志
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" style="margin-right: 8px;"> 错误日志
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" style="margin-right: 8px;"> 调试日志
                    </label>
                    <label style="display: flex; align-items: center; padding: 10px; background: white; border-radius: 4px; border: 1px solid #e0e0e0; cursor: pointer;">
                        <input type="checkbox" checked style="margin-right: 8px;"> 统计数据
                    </label>
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 15px; border-radius: 6px; margin-bottom: 15px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">时间范围</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                    <input type="datetime-local" value="2024-10-23T00:00" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                    <input type="datetime-local" value="2024-10-23T23:59" style="padding: 10px; border: 1px solid #bdc3c7; border-radius: 4px;">
                </div>
            </div>
            
            <div style="background: #f8f9fa; padding: 15px; border-radius: 6px;">
                <label style="display: block; color: #7f8c8d; margin-bottom: 8px; font-size: 13px;">导出格式</label>
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
                    <button class="btn btn-primary" onclick="exportFormat('TXT')">TXT文本</button>
                    <button class="btn btn-primary" onclick="exportFormat('CSV')">CSV表格</button>
                    <button class="btn btn-primary" onclick="exportFormat('JSON')">JSON数据</button>
                </div>
            </div>
        </div>
        
        <div style="background: #e3f2fd; padding: 12px; border-radius: 6px; border-left: 4px solid #3498db;">
            <div style="color: #2c3e50; font-size: 13px;">
                <strong>预计文件大小:</strong> <span style="color: #3498db; font-weight: 600;">约 15.8 MB</span><br>
                <strong>记录条数:</strong> <span style="color: #3498db; font-weight: 600;">约 24,560 条</span>
            </div>
        </div>
    `;
    
    showModal('导出算法日志', html);
}

function exportFormat(fmt) {
    showToast(`正在导出${fmt}格式日志文件`, 'info');
    setTimeout(() => {
        showToast(`日志文件已保存: algorithm_log_${new Date().getTime()}.${fmt.toLowerCase()}`, 'success');
        closeModal();
    }, 1500);
}

function resetAlgorithms() {
    if (confirm('确定重置所有算法参数？将恢复出厂默认设置。')) {
        showToast('正在重置算法参数...', 'info');
        setTimeout(() => {
            showToast('算法参数已重置为默认值', 'success');
        }, 1500);
    }
}

// ========== 页面7: 系统服务 - 人工客服功能 ==========

// 在线客服
function showCustomerService() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div style="font-size: 48px; color: #667eea; margin-bottom: 10px;">客服中心</div>
            <div style="font-size: 14px; color: #7f8c8d;">7x24小时为您服务</div>
        </div>
        
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 15px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px; font-size: 15px;">联系方式</div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #3498db;">
                    <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">客服热线</div>
                    <div style="font-size: 20px; color: #3498db; font-weight: 700;">400-888-6688</div>
                </div>
                <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #27ae60;">
                    <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">技术支持</div>
                    <div style="font-size: 20px; color: #27ae60; font-weight: 700;">0771-1234567</div>
                </div>
            </div>
            
            <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #f39c12; margin-bottom: 15px;">
                <div style="font-size: 12px; color: #7f8c8d; margin-bottom: 5px;">售后邮箱</div>
                <div style="font-size: 16px; color: #f39c12; font-weight: 600;">support@gzjy.com</div>
            </div>
            
            <div class="info-row"><span>工作时间:</span><span style="color: #27ae60; font-weight: 600;">周一至周日 8:00-20:00</span></div>
            <div class="info-row"><span>当前在线客服:</span><span class="badge badge-success">5名</span></div>
            <div class="info-row"><span>平均响应时间:</span><span style="color: #3498db; font-weight: 600;">2分钟</span></div>
        </div>
        
        <div style="background: #e8f5e9; padding: 15px; border-radius: 6px; border-left: 4px solid #27ae60; margin-bottom: 15px;">
            <div style="font-weight: 600; color: #155724; margin-bottom: 10px;">在线留言</div>
            <textarea style="width: 100%; height: 80px; padding: 10px; border: 1px solid #ced4da; border-radius: 4px; resize: vertical; font-size: 13px;" placeholder="请输入您的问题或建议..."></textarea>
            <div style="margin-top: 10px; text-align: right;">
                <button class="btn btn-success" onclick="submitMessage()">提交留言</button>
            </div>
        </div>
        
        <div style="font-size: 12px; color: #95a5a6; text-align: center;">
            客服将在收到留言后第一时间与您联系
        </div>
    `;
    
    showModal('联系在线客服', html);
}

// 技术支持
function showTechnicalSupport() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div style="font-size: 48px; color: #f093fb; margin-bottom: 10px;">技术支持</div>
            <div style="font-size: 14px; color: #7f8c8d;">专业技术团队为您保驾护航</div>
        </div>
        
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 15px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px; font-size: 15px;">支持服务类型</div>
            
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px;">
                <div style="background: white; padding: 12px; border-radius: 6px; border: 2px solid #3498db; text-align: center; cursor: pointer;" onclick="selectSupport('remote')">
                    <div style="font-weight: 600; color: #3498db; margin-bottom: 5px;">远程协助</div>
                    <div style="font-size: 11px; color: #7f8c8d;">在线远程诊断</div>
                </div>
                <div style="background: white; padding: 12px; border-radius: 6px; border: 2px solid #27ae60; text-align: center; cursor: pointer;" onclick="selectSupport('onsite')">
                    <div style="font-weight: 600; color: #27ae60; margin-bottom: 5px;">现场服务</div>
                    <div style="font-size: 11px; color: #7f8c8d;">工程师上门</div>
                </div>
            </div>
            
            <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #e74c3c; margin-bottom: 15px;">
                <div style="font-weight: 600; color: #c0392b; margin-bottom: 10px;">紧急故障热线</div>
                <div style="font-size: 24px; color: #e74c3c; font-weight: 700;">0771-1234567</div>
                <div style="font-size: 11px; color: #7f8c8d; margin-top: 5px;">承诺30分钟内响应</div>
            </div>
            
            <div class="info-row"><span>技术支持时间:</span><span style="color: #27ae60; font-weight: 600;">7x24小时</span></div>
            <div class="info-row"><span>在线工程师:</span><span class="badge badge-success">3名</span></div>
            <div class="info-row"><span>服务覆盖:</span><span style="color: #3498db; font-weight: 600;">全国200+城市</span></div>
        </div>
        
        <div style="background: #fff3cd; padding: 15px; border-radius: 6px; border-left: 4px solid #f39c12;">
            <div style="font-weight: 600; color: #856404; margin-bottom: 10px;">故障申报</div>
            <div style="margin-bottom: 8px;">
                <select style="width: 100%; padding: 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 13px;">
                    <option>请选择故障类型</option>
                    <option>硬件故障</option>
                    <option>软件异常</option>
                    <option>通讯问题</option>
                    <option>性能问题</option>
                    <option>其他问题</option>
                </select>
            </div>
            <div style="margin-bottom: 8px;">
                <textarea style="width: 100%; height: 70px; padding: 10px; border: 1px solid #ced4da; border-radius: 4px; resize: vertical; font-size: 13px;" placeholder="请详细描述故障现象..."></textarea>
            </div>
            <div style="text-align: right;">
                <button class="btn btn-warning" onclick="submitFaultReport()">提交故障申报</button>
            </div>
        </div>
    `;
    
    showModal('技术支持服务', html);
}

// 意见反馈
function showFeedback() {
    const html = `
        <div style="text-align: center; margin-bottom: 20px;">
            <div style="font-size: 48px; color: #4facfe; margin-bottom: 10px;">意见反馈</div>
            <div style="font-size: 14px; color: #7f8c8d;">您的反馈是我们前进的动力</div>
        </div>
        
        <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 15px;">
            <div style="font-weight: 600; color: #2c3e50; margin-bottom: 15px; font-size: 15px;">反馈类型</div>
            
            <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 15px;">
                <div style="background: white; padding: 10px; border-radius: 6px; border: 2px solid #3498db; text-align: center; cursor: pointer; font-size: 12px;" onclick="selectFeedbackType('suggestion')">
                    <div style="font-weight: 600; color: #3498db;">功能建议</div>
                </div>
                <div style="background: white; padding: 10px; border-radius: 6px; border: 2px solid #f39c12; text-align: center; cursor: pointer; font-size: 12px;" onclick="selectFeedbackType('bug')">
                    <div style="font-weight: 600; color: #f39c12;">Bug反馈</div>
                </div>
                <div style="background: white; padding: 10px; border-radius: 6px; border: 2px solid #27ae60; text-align: center; cursor: pointer; font-size: 12px;" onclick="selectFeedbackType('experience')">
                    <div style="font-weight: 600; color: #27ae60;">体验反馈</div>
                </div>
            </div>
            
            <div style="background: white; padding: 15px; border-radius: 6px; border-left: 4px solid #3498db; margin-bottom: 15px;">
                <div style="font-weight: 600; color: #2c3e50; margin-bottom: 10px;">反馈内容</div>
                <div style="margin-bottom: 8px;">
                    <input type="text" style="width: 100%; padding: 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 13px;" placeholder="标题（必填）">
                </div>
                <div style="margin-bottom: 8px;">
                    <textarea style="width: 100%; height: 100px; padding: 10px; border: 1px solid #ced4da; border-radius: 4px; resize: vertical; font-size: 13px;" placeholder="请详细描述您的反馈内容...（必填）"></textarea>
                </div>
                <div style="margin-bottom: 8px;">
                    <input type="text" style="width: 100%; padding: 8px; border: 1px solid #ced4da; border-radius: 4px; font-size: 13px;" placeholder="联系方式（选填）">
                </div>
            </div>
            
            <div style="background: #e3f2fd; padding: 12px; border-radius: 6px; border-left: 4px solid #2196f3; margin-bottom: 15px;">
                <div style="font-size: 12px; color: #1976d2; line-height: 1.6;">
                    <strong>感谢您的反馈!</strong><br>
                    我们承诺在24小时内审阅您的意见，并在48小时内给予回复。<br>
                    您的每一条建议都将被认真对待。
                </div>
            </div>
            
            <div style="text-align: center;">
                <button class="btn btn-primary" onclick="submitFeedback()">提交反馈</button>
                <button class="btn btn-default" style="margin-left: 10px;" onclick="closeModal()">取消</button>
            </div>
        </div>
        
        <div style="font-size: 12px; color: #95a5a6; text-align: center;">
            已收到反馈 <span style="color: #3498db; font-weight: 600;">1,258</span> 条，采纳 <span style="color: #27ae60; font-weight: 600;">823</span> 条
        </div>
    `;
    
    showModal('意见反馈', html);
}

// 提交留言
function submitMessage() {
    showToast('留言已提交，客服将尽快与您联系', 'success');
    setTimeout(() => {
        closeModal();
    }, 1500);
}

// 选择技术支持类型
function selectSupport(type) {
    if (type === 'remote') {
        showToast('正在连接远程协助系统...', 'info');
    } else if (type === 'onsite') {
        showToast('工程师将在24小时内联系您', 'success');
    }
}

// 提交故障申报
function submitFaultReport() {
    showToast('故障申报已提交，工程师将在30分钟内响应', 'success');
    setTimeout(() => {
        closeModal();
    }, 1500);
}

// 选择反馈类型
function selectFeedbackType(type) {
    const types = {
        'suggestion': '功能建议',
        'bug': 'Bug反馈',
        'experience': '体验反馈'
    };
    showToast(`已选择: ${types[type]}`, 'info');
}

// 提交反馈
function submitFeedback() {
    showToast('感谢您的反馈，我们将认真处理', 'success');
    setTimeout(() => {
        closeModal();
    }, 1500);
}

// 关闭弹窗时清理
window.addEventListener('beforeunload', () => {
    if (sensorTimer) clearInterval(sensorTimer);
});

console.log('弹窗系统已加载');
